是否可以将表达式树中的变量向下转换为由Expression.Parameter(typeof(Type))关闭的已知泛型派生?

时间:2017-03-03 19:24:53

标签: c# expression-trees linq-expressions

我有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();        
   }
}

0 个答案:

没有答案