jeudi 10 décembre 2020

Getting the properties defined in an anonymous type sent via Func

Let's say we have the following classes defined like this

class Test {
    public string Name { get; set; }
    public string Type { get; set; }
    public string SomeOtherValue { get; set; }
    public Address Address { get; set; }
}

class Address {
    public string AddressText { get; set; }
    public string PostalCode { get; set; }
}

Then I have a need inside a method to do something with one or more of the properties in this class, and I would like to define which in a compile safe way. So I want to call the method like this:

MyFunction<Test>(t => new {t.Name, t.Address.AddressText});

Then inside MyFunction I need to know that "Name" and "Address.AddressText" are the selected properties, but I'm not sure how to get a hold of that

public void MyFunction<T>(Func<T, ?> param){
    ...
}

So my problem is I can't set the ? as the TResult of Func in any good way. If I could set that properly I guess I could take typeOf(TResult).GetProperties(), but I feel I'm missing a piece to get this to work.





Aucun commentaire:

Enregistrer un commentaire