How do I set a field value in an C# Expression tree?

后端 未结 6 603
野趣味
野趣味 2020-12-02 08:16

Given:

FieldInfo field = ;
ParameterExpression targetExp = Expression.Parameter(typeof(T), \"target\");
ParameterExp         


        
6条回答
  •  庸人自扰
    2020-12-02 08:48

    Setting a field is, as already discussed, problematic. You can can (in 3.5) a single method, such as a property-setter - but only indirectly. This gets much easier in 4.0, as discussed here. However, if you actually have properties (not fields), you can do a lot simply with Delegate.CreateDelegate:

    using System;
    using System.Reflection;
    public class Foo
    {
        public int Bar { get; set; }
    }
    static class Program
    {
        static void Main()
        {
            MethodInfo method = typeof(Foo).GetProperty("Bar").GetSetMethod();
            Action setter = (Action)
                Delegate.CreateDelegate(typeof(Action), method);
    
            Foo foo = new Foo();
            setter(foo, 12);
            Console.WriteLine(foo.Bar);
        }
    }
    

提交回复
热议问题