方法名称是否隐式转换为委托类型? [英] Are method names implicitly cast to delegate types?

查看:132
本文介绍了方法名称是否隐式转换为委托类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个代表,当我输入ay字符时,我将调用:

  public delegate void respondToY(string msgToSend); 

private respondToY yHandler;

我有一个订阅方法,以便调用代码可以要求在委托被调用时通知:

  public void Subscribe(respondToY methodName)
{
yHandler + = methodName;
}

据我所知,要注册该代表,我需要提供一些类型respondToY的东西。然而,当调用subscribe方法时,我可以提供一个新的代理实例或简单的方法的名称。这是否意味着可以使用与代理签名相匹配的任何方法,并将自动转换为正确的委托类型?



**编辑**



所以在这个假设下,只提供一个方法名称,例如click按钮的按钮事件处理程序(如果该方法使用了发件人和相关的事件对象),那么它将是有效的转换为所需的委托?

解决方案

这是一个方法组转换。它将方法组(基本上是方法的名称或重载的方法)转换为具有兼容签名的委托类型的实例。



是的,任何兼容的方法都可以用过的。请注意,您也可以提供目标,例如:

  string text =Hello there; 
Func< int,int,string> func = text.Substring;

Console.WriteLine(func(2,3)); //打印llo,这是text.Substring(2,3)

必须是一个特定的委托类型。你不能只使用:

 委托x = methodName; 

...编译器不知道要创建的委托类型。



有关更多信息,请参阅C#4语言规范的6.6节。



请注意,方法组转换始终创建一个新的委托代理实例 - 它不被缓存(不能违反规范。)


Im having a little trouble understanding delegates.

I have a delegate that i will invoke when a y character is entered:

public delegate void respondToY(string msgToSend);

        private respondToY yHandler;

i have a subscribe method in order that calling code can ask to be notified when the delegate is invoked:

public void Subscribe(respondToY methodName)
        {
            yHandler += methodName;
        }

As far as i can see, to register with this delegate, i need to provide something of the type respondToY. Yet when calling the subscribe method, i can supply either a new instance of the delegate or simply the name of the method. Does this mean that any method matching the delegate signature can be used and will automatically be converted to the correct delegate type?

** Edit **

So on this assumption it would also be valid to supply only a method name to things like click event handlers for buttons (provided the method took the sender, and the relevant event object), it would be converted to the required delegate?

解决方案

This is a method group conversion. It converts a method group (basically the name of a method or overloaded methods) to an instance of a delegate type with a compatible signature.

Yes, any compatible method can be used. Note that you can provide a target too - for example:

string text = "Hello there";
Func<int, int, string> func = text.Substring;

Console.WriteLine(func(2, 3)); // Prints "llo", which is text.Substring(2, 3)

There must be a specific delegate type involve though. You can't just use:

Delegate x = methodName;

... the compiler doesn't know the kind of delegate to create.

For more information, see section 6.6 of the C# 4 language specification.

Note that a method group conversion always creates a new instance of the delegate in question - it isn't cached (and can't be without violating the specification.)

这篇关于方法名称是否隐式转换为委托类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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