I have an Expression.Call
which uses Expression.Parameter(typeof(Type))
to return an instance of type SomeType
, which is in fact a derived class SomeType<T>
with a field SomeField
of type T
where T
is the parameter value.
Is it possible to construct a LambdaExpression<Func<Type,object>>
that can be compiled to return the SomeField
field value? ( Aside from creating expressions to call FieldInfo.GetValue
through expressions ! Or through a create method that provides the type as parameter or generic parameter.)
public class SomeType
{
public static SomeType Create(Type tType)
{
return (SomeType)typeof(SomeType<>).MakeGenericType(tType)
.GetConstructor(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance, null, new Type[] { tType }, null)
.Invoke(new object[] { Activator.CreateInstance(tType) });
}
}
public class SomeType<T> : SomeType where T:new()
{
internal SomeType(T someField)
{
SomeField = someField;
}
public T SomeField;
}
public class GetFieldValue{
public object NormalGetFieldValue(Type t){
var someType = SomeType.Create(t);
return someType.GetType().GetField("SomeField").GetValue(someType);
}
private Func<Type,object> compiledLambdaExpression;
public object UseCompiledLamda(Type t){
return compiledLambdaExpression(t);
}
public void How_Do_I_Create_Compiled_LambdaExpression????(){
//of course can do the following
//(t)=>{ //the code in NormalGetFieldValue }
// or Delegate.CreateDelegate
//Is it possible to create body below given restrictions mentioned ???
//var paramExpr=Expresison.Parameter(typeof(Type));
//Expression body=.................
//compiledLambdaExpression=Expression.Lambda<Func<Type,object>>(
//body,paramExpr).Compile();
}
}