Is there a delegate available for properties in C#?

后端 未结 3 1577
无人及你
无人及你 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条回答
  •  猫巷女王i
    2020-12-28 10:40

    You could create the delegate using reflection :

    Action valueSetter = (Action)Delegate.CreateDelegate(typeof(Action), tc, tc.GetType().GetProperty("Value").GetSetMethod());
    

    or create a delegate to an anonymous method which sets the property;

    Action valueSetter = v => tc.Value = v;
    

    Edit: used wrong overload for CreateDelegate(), need to use the one that takes and object as target. Fixed.

提交回复
热议问题