C#委托不绑定到一个实例? [英] C# delegate not bound to an instance?

查看:179
本文介绍了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 .net 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#委托不绑定到一个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆