2

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();        
   }
}
user487779
  • 550
  • 5
  • 12
  • 1
    Can you maybe show some code of what you're trying to do? – smead Mar 03 '17 at 23:31
  • Is [this](http://stackoverflow.com/questions/293905/reflection-getting-the-generic-parameters-from-a-system-type-instance) what you're trying to do? – smead Mar 03 '17 at 23:32
  • @smead code provided. This is an expression tree question. – user487779 Mar 04 '17 at 11:39
  • 2
    I don't think this is how you use linq's expressions. Accessors are fast because they are compiled for each type separately. If you're going to have type-agnostic code inside the accessor, it's not going to be better than `NormalGetFieldValue`. – GSerg Mar 05 '17 at 10:02
  • @GSerg It was an exercise in playing with expression trees, was making sure there was nothing that I had missed. – user487779 Mar 06 '17 at 08:56

0 Answers0