从属性 getter 或 setter 方法创建委托

Create a delegate from a property getter or setter method(从属性 getter 或 setter 方法创建委托)
本文介绍了从属性 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 方法创建委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)