Create shared Func from reflection
I have a variable type: Type hiddenType
. I need to create a delegate Func<T>
where it T
has the type specified in the specified variable and assigns a method:
var funcType = typeof(Func<>).MakeGenericType(hiddenType);
Func<object> funcImplementation = () => GetInstance(hiddenType);
var myFunc= Delegate.CreateDelegate(funcType , valueGenerator.Method);
It doesn't work because it funcImplementation
returns object
instead of what you want. At run time, it will necessarily be an instance of the type specified in hiddenType
.
GetInstance
returns object
, and signaure cannot be changed.
This can be solved by building the expression tree by hand and entering a cast in hiddenType
. This is allowed when building an expression tree.
var typeConst = Expression.Constant(hiddenType);
MethodInfo getInst = ... // <<== Use reflection here to get GetInstance info
var callGetInst = Expression.Call(getInst, typeConst);
var cast = Expression.Convert(callGetInst, hiddenType);
var del = Expression.Lambda(cast).Compile();
Note: the above code assumes that GetInstance
- static
. If it's not static, change the way you create callGetInst
pass the object the method is called on.
source to share
Instead of using a type, you can use a generic wrapper if you were unable to change the signature of GetInstance:
private Func<THidden> GetTypedInstance<THidden>()
{
return () => (THidden)GetInstance(typeof(THidden));
}
Then you can just call it with
GetTypedInstance<SomeClass>();
instead
GetInstance(typeof(SomeClass));
source to share