Is there a way to create a delegate to get and set values for a FieldInfo?

后端 未结 8 2019
闹比i
闹比i 2020-12-08 08:18

For properties there are GetGetMethod and GetSetMethod so that I can do:

Getter = (Func)Delegate.CreateDelegate(typeof(         


        
8条回答
  •  醉酒成梦
    2020-12-08 08:37

    Just to add more ways of doing it :D

     public static Func CreatePropertyOrFieldReaderDelegate(string field)
            {
                var input = Expression.Parameter(typeof(T));
                return Expression.Lambda>(Expression.PropertyOrField(input, field), input).Compile();
            }
    
    

    This will create a method that returns the value..

    TEST CASE

    class Testing {
      public int Data = 2;
      public string PropData { get; } = "Default";
     }
    
    
      [Fact]
      public void CreateSingleFieldReader()
            {
                var a = ReflectionHelper.CreatePropertyOrFieldReaderDelegate("Data");
                Assert.Equal(2, a(new Testing()));
    
            }
    

提交回复
热议问题