Create a delegate from a property getter or setter method(从属性 getter 或 setter 方法创建委托)
问题描述
要从方法创建委托,您可以使用编译类型安全语法:
To create a delegate from a method you can use the compile type-safe syntax:
private int Method() { ... }
// and create the delegate to Method...
Func<int> d = Method;
属性是 getter 和 setter 方法的包装,我想为属性 getter 方法创建一个委托.类似的东西
A property is a wrapper around a getter and setter method, and I want to create a delegate to a property getter method. Something like
public int Prop { get; set; }
Func<int> d = Prop;
// or...
Func<int> d = Prop_get;
不幸的是,这不起作用.我必须创建一个单独的 lambda 方法,当 getter 方法与委托签名匹配时,这似乎是不必要的:
Which doesn't work, unfortunately. I have to create a separate lambda method, which seems unnecessary when the getter method matches the delegate signature anyway:
Func<int> d = () => Prop;
为了直接使用委托方法,我必须使用讨厌的反射,这不是编译类型安全的:
In order to use the delegate method directly, I have to use nasty reflection, which isn't compile type-safe:
// something like this, not tested...
MethodInfo m = GetType().GetProperty("Prop").GetGetMethod();
Func<int> d = (Func<int>)Delegate.CreateDelegate(typeof(Func<int>), m);
有没有什么方法可以直接以编译安全的方式在属性获取方法上创建委托,类似于在顶部的普通方法上创建委托,而无需使用中间 lambda 方法?
Is there any way of creating a delegate on a property getting method directly in a compile-safe way, similar to creating a delegate on a normal method at the top, without needing to use an intermediate lambda method?
推荐答案
据我所知,您已经写下了所有有效"的变体.由于无法在普通代码中显式处理 getter 或 setter(即没有反射),我认为没有办法做你想做的事.
As far as I can tell, you have already written down all "valid" variants. Since it isn't possible to explicitly address a getter or setter in normal code (without reflection, that is), I don't think that there is a way to do what you want.
这篇关于从属性 getter 或 setter 方法创建委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从属性 getter 或 setter 方法创建委托
- C# 中多线程网络服务器的模式 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04