Is there a delegate available for properties in C#?

后端 未结 3 1582
无人及你
无人及你 2020-12-28 10:04

Given the following class:

class TestClass {
  public void SetValue(int value) { Value = value; }
  public int Value { get; set; }
}

I can

3条回答
  •  清歌不尽
    2020-12-28 10:15

    There are three ways of doing this; the first is to use GetGetMethod()/GetSetMethod() and create a delegate with Delegate.CreateDelegate. The second is a lambda (not much use for reflection!) [i.e. x=>x.Foo]. The third is via Expression (.NET 3.5).

    The lambda is the easiest ;-p

        class TestClass
        {
            public int Value { get; set; }
        }
        static void Main()
        {
            Func lambdaGet = x => x.Value;
            Action lambdaSet = (x, val) => x.Value = val;
    
            var prop = typeof(TestClass).GetProperty("Value");
            Func reflGet = (Func) Delegate.CreateDelegate(
                typeof(Func), prop.GetGetMethod());
            Action reflSet = (Action)Delegate.CreateDelegate(
                typeof(Action), prop.GetSetMethod());
        }
    

    To show usage:

            TestClass foo = new TestClass();
            foo.Value = 1;
            Console.WriteLine("Via property: " + foo.Value);
    
            lambdaSet(foo, 2);
            Console.WriteLine("Via lambda: " + lambdaGet(foo));
    
            reflSet(foo, 3);
            Console.WriteLine("Via CreateDelegate: " + reflGet(foo));
    

    Note that if you want the delegate pointing to the specific instance, you can use closures for the lambda, or the overload of CreateDelegate that accepts and instance.

提交回复
热议问题