mercredi 5 juin 2019

Make properties of a class parameters to a function

My intention is to pass public properties of a class, like say:

class MyTestClass
{
    public string Name { get; set; }
    public DateTime  StartedAt { get; set; }
    public TimeSpan Duration { get; set; }
}

to a function a parameters:

static void MyCustomFunc(params Expression<Func<MyTestClass, object>>[] props)
{
    foreach (var p in props)
    {
        // The following only works for Name property, not for StartedAt or Duration
        MemberExpression member = p.Body as MemberExpression;
        PropertyInfo propertyInfo = (PropertyInfo)member.Member;

        string name = propertyInfo.Name;
        Type type = propertyInfo.PropertyType;
        Func<MyTestClass, object> func = p.Compile();
    }
}

The function is supposed to gather this info and feed it into an exporter class that exports sets of MyTestClass objects to a CSV file.

The output written to the CSV file is dependent on the number, type and order of properties fed into MyCustomFunc.

So this:

MyCustomFunc(x => x.Name, x => x.StartedAt);

produces a different result from:

MyCustomFunc(x => x.StartedAt, x => x.Name);

and

MyCustomFunc(x => x.StartedAt, x => x.Name, x => x.Duration);

is different from

MyCustomFunc(x => x.Duration, x => x.StartedAt, x => x.Name);

My problem is making the reflection work. The code of the foreach loop is buggy: for {x => x.Name} I'm getting the correct info for name, type and func. But for {x => x.StartedAt} or {x => x.Name} I'm getting a null reference exception.





Aucun commentaire:

Enregistrer un commentaire