是否有一个代表可在C#中的属性? [英] Is there a delegate available for properties in C#?

查看:102
本文介绍了是否有一个代表可在C#中的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于以下类:

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



我可以做

I can do

TestClass tc = new TestClass();
Action<int> setAction = tc.SetValue;
setAction.Invoke(12);



这是所有好。是否有可能使用属性而不是方法做同样的事情?最好有内置到.NET的东西。

which is all good. Is it possible to do the same thing using the property instead of the method? Preferably with something built in to .net.

推荐答案

您可以使用反射创建委托:

You could create the delegate using reflection :

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

或创建一个委托给它设定了财产匿名方法;

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

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



编辑:使用错误的过载createDelegate方法(),需要使用一个接受和对象作为目标。固定的。

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

这篇关于是否有一个代表可在C#中的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆