我有Expression.Call
使用Expression.Parameter(typeof(Type))
来返回SomeType
类型的实例,实际上这是一个带有字段SomeType<T>
的派生类SomeField
类型T
,其中T
是参数值。
是否可以构造一个LambdaExpression<Func<Type,object>>
来编译以返回SomeField
字段值? (除了创建通过表达式调用FieldInfo.GetValue
的表达式之外!还是通过提供类型作为参数或泛型参数的create方法。)
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();
}
}