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 方法创建委托
基础教程推荐
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- WPF 模态进度窗口 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
