[英]Delegate to property
I would like to get a delegate to a property´s set function. 我想获得一个属性的set函数的委托。 This is how I do today:
这就是我今天的表现:
var property = typeof(IApplicationState).GetProperty(propertyName);
var action = (Action<IApplicationState, T>)Delegate.CreateDelegate(typeof(Action<IApplicationState, T>), null, property.GetSetMethod());
This works, but then I have know the name of the property. 这有效,但后来我知道该属性的名称。
Can I do this without using the name? 我可以不使用这个名字吗? Something like this:
像这样的东西:
var action = (Action<IApplicationState, T>)Delegate.CreateDelegate(typeof(Action<IApplicationState, T>), null, IApplicationState.PROPERTY.GetSetMethod());
One simple option which does introduce an extra hop (but would probably have negligible performance impact) would be to just use a lambda expression: 一个简单的选项确实引入了额外的跳(但可能会产生可忽略的性能影响),只需使用lambda表达式:
Action<IApplicationState, T> action = (state, value) => state.Foo = value;
There's currently no way of referring to a property at compile-time in the same way as we can refer to a type with typeof
- although it's on the C# team's feature request list. 目前无法在编译时引用属性,就像我们可以引用具有
typeof
的类型一样 - 尽管它位于C#团队的功能请求列表中。
EDIT: If this is in a generic method (with a type parameter of T
), it's not at all clear to me that you'll be able to use this directly, as state.Foo
would presumably have to be of type T
(or object
perhaps). 编辑:如果这是一个通用的方法(类型参数为
T
),我完全不清楚你是否可以直接使用它,因为state.Foo
可能必须是T
型(或者object
也许)。 We can't really help with that aspect without more context of what you're trying to achieve. 如果没有更多关于你想要达到的目标的背景,我们就无法真正帮助你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.