I would like to "wrap" the getter function for a specific property that is part of a specific type. I have an abstract class defined as follows:
public abstract class MyAbstractClass<T> where T : MyType {
Ok, suppose I have a specific class, like the following:
public abstract class MyConcreteClass : MyAbstractClass<MyConcreteType> {
And now, a helper method that should return a wrapper for the getter method:
private Func<MyAbstractClass<T>, Object> GetPropertyGetter(PropertyInfo property) { var instanceType = Expression.Parameter(property.DeclaringType, "i"); // Taking getter "body". var getterBody = Expression.Property(instanceType, property); // Cast to a generic Object. var body = Expression.TypeAs(getterBody, typeof(Object)); // Build the expression. var exp = Expression.Lambda<Func<MyAbstractClass<T>, Object>>(body, instanceType); return exp.Compile(); }
As expected, I get the following exception:
The Expression of type 'MyConcreteClass' cannot be used to delegate a parameter of type 'MyAbstractClass <MyConcreteType>'.
Is there any way to βforceβ this kind of casting? Thanks in advance.
Nicolabaldi
source share