mardi 6 octobre 2015

Dynamic/ Expression based way to get property type of a class?

I currently have a function that gets the type of a property of an object and it can be seen below.

private static Type GetPropertyType<TClass, TResult>(Expression<Func<TClass, TResult>> propertyExpression)
{
    Type type = propertyExpression.Body.Type;
    if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
    {
        type = Nullable.GetUnderlyingType(type);
    }
    return type;
}

Now, the problem with this is that i need to have an instance of the object that i intend to get the type of the property as seen below

var baseZoneTypeEntity = zoneType.First();
GetPropertyType(() => baseZoneTypeEntity.BonusAmount);

I would like to have something like you pass the class instead of passing an instance, so something

GetPropertyType<ZoneTypeClass>(_ => _.BonusAmount);

Expressions are quite new to me and im trying to convert this for half an hour already and to no avail.

Can you guys help me convert this to a class based from an object based one?

Thank you.





Aucun commentaire:

Enregistrer un commentaire