C#委托不绑定到一个实例?

编程入门 行业动态 更新时间:2024-10-28 15:32:06
本文介绍了C#委托不绑定到一个实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有没有来存储一个委托不绑定到一个对象怎么样,你可以用一个MethodInfo的一种方式?现在我储存的MethodInfo这样我就可以给它的对象调用该方法。但我更愿意把它成为一个代表。就像是有告诉.NET的第一个参数是本

MethodInfo的MI属性?; 动作<串GT; FUNC; mi.Invoke(这一点,新的对象[] {STR}); FUNC(这一点,STR); //这是可能的一个代表?

解决方案

您想要什么叫做的打开的实例委托。它不是在C#语言直接支撑,但在CLR支持它。

基本上,一个开放的实例委托是一样的正常委托,但它需要一个为这个额外的参数正常参数之前,并且有一个空的目标(像一个静态方法的委托)。例如,实例相当于动作<开放; T> 是:

委托无效OpenAction< TThis,T>(TThis @this,T ARG);

下面是一个完整的例子:

无效的主要() { MethodInfo的sayHelloMethod = typeof运算(人).GetMethod(的SayHello); OpenAction<人,串GT;行动= (OpenAction<人,串>) Delegate.CreateDelegate(的typeof(OpenAction<人,串>),空, sayHelloMethod); 的人乔=新的Person {名=乔}; 动作(乔,杰克); //输出杰克你好,我的名字是乔} 委托无效OpenAction< TThis,T>(TThis @this,T ARG); 类Person {公共字符串名称{;组; } 公共无效的SayHello(字符串名称) { Console.WriteLine(嗨{0},我的名字是{1},名称,this.Name); } }

有一个看的这篇文章了解更多详情。

Is there a way to store a delegate without binding it to an object like how you can with a MethodInfo? Right now I am storing a MethodInfo so I can give it the object to call the method for. But I much rather have it be a delegate. Like is there an attribute that tells that the first parameter is "this"?

MethodInfo mi; Action<string> func; mi.Invoke(this,new object[]{str}); func(this, str); //Is this possible with a delegate?

解决方案

What you want is called an open instance delegate. It isn't supported directly in the C# language, but the CLR supports it.

Basically, an open instance delegate is the same as a normal delegate, but it takes an extra parameter for this before the normal parameters, and has a null target (like a delegate for a static method). For instance, the open instance equivalent of Action<T> would be:

delegate void OpenAction<TThis, T>(TThis @this, T arg);

Here's a complete example:

void Main() { MethodInfo sayHelloMethod = typeof(Person).GetMethod("SayHello"); OpenAction<Person, string> action = (OpenAction<Person, string>) Delegate.CreateDelegate( typeof(OpenAction<Person, string>), null, sayHelloMethod); Person joe = new Person { Name = "Joe" }; action(joe, "Jack"); // Prints "Hello Jack, my name is Joe" } delegate void OpenAction<TThis, T>(TThis @this, T arg); class Person { public string Name { get; set; } public void SayHello(string name) { Console.WriteLine ("Hi {0}, my name is {1}", name, this.Name); } }

Have a look at this article for more details.

更多推荐

C#委托不绑定到一个实例?

本文发布于:2023-05-29 16:44:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/348718.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:绑定   实例

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!