C# delegate question [duplicate]
Possible Dup开发者_JAVA技巧licate:
What is Delegate?
In C#, a delegate can be seen as both method name and type name. Is my understanding right?
like "doShow[] items = new doShow[3];" dowShow is type name. like "doshow(new Class1()....)" dosShow is a method name/
I get this conclusion by reading codes here:
public class TestDelegate
{
// define a datatype as a method taking a string returning void
public delegate void doShow(String s);
public static void Main(string[] args)
{
// make an array of these methods
doShow[] items = new doShow[3];
items[0] = new doShow(new Class1().show);
items[1] = new doShow(new Class2().display);
items[2] = new doShow(Class3.staticDisplay);
// call all items the same way
for(int i = 0; i < items.Length; i++) {
items[i]("Hello World");
}
}
}
Yes. A delegate type is a type. An instance of a delegate type can be invoked like a method with (method syntax myDelegate(arg1, arg2)
). A delegate can be thought of as a strongly typed (hence the Type) method pointer.
If I am not wrong, delegate is always a type, but its instance can be associated to a method with the identical signature. This is what you are seeing in the above code.
doShow is a type and then its instances (using the new operator) are associated with the methods passed as parameters to the constructor of the delegate.
Vijay
You shouldn't think of delegates themselves as "methods", even though you can use instances of them in much the same way. They are not methods, they are types.
They are a special type, instances of which can hold references to methods. The "name" you give to a delegate is not a method name, it's a type name, like any class, enum, etc. That type just happens to describe an object that can be executed by calling it, just like a method.
It's important to make the distinction between a delegate and "a method name" for several reasons:
Most importantly -- you don't use the delegate type name itself to call the associated methods. You use the instance name. Given your sample, you cannot say:
doShow("Hi");
A delegate can hold a reference to an anonymous method that has no name, such as:
doShow s = delegate ( string s ) { Console.WriteLine(s); };
A delegate can hold a reference to a lamba expression, which is internally just a different way to write an anonymous delegate method, but superficially looks completely different:
doShow s = x => Console.WriteLine(x);
Multi-cast delegates (such as event handlers) can hold references to more than one method at a time, including any combination of named methods, anonymous methods, or lambas.
myObject.MyEvent += ObjectEvent; myObject.MyEvent += delegate ( object sender, EventArgs e ) { Console.WriteLine("Hi"); } myObject.MyEvent += ( sender, e ) => Console.WriteLine("Hi again.");
精彩评论