Are method names implicitly cast to delegate types

2019-03-27 05:42发布

问题:

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?

回答1:

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.)



回答2:

as far as i know ... yes, the delegate type just makes sure that the signatures match



标签: c# delegates