What is delegate and how it allows to create objects [closed]
开发者_开发问答
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this questionIf delegates are Abstract then how it allows to create object
Here's a link to one of the best essays on C# delegates I have found, and the author does a great job of providing an entertaining and informative walkthrough of how delegates work and why we use them.
http://www.sellsbrothers.com/writing/default.aspx?content=delegates.htm
delegate is a type safe function pointer. It is a reference type in C#.
delegate result-type identifier ([parameters]);
However the Delegate class is not a delegate type, it's a class used to derive delegate types, thus it is abstract (check for more clarification).
A delegate looks like a typesafe function pointer, of course to understand that you'd need to know what a function pointer is and why typesafety is important, but it's more than that.
Under the covers a delegate is a class with an Invoke method, the Invoke method is created at compile time to have the same signature as the delegate definition. So if I do
delegate int MyDelegate(string s);
I'd end up with something like
class MyDelegate : MulticastDelegate
{
int Invoke(string s) {...}
}
I can use this in code like this
int SomeFunc(string s)
{
// do something with s and return an int
}
MyDelegate del = new MyDelegate(SomeFunc);
then either
int a = del.Invoke("Foo");
or simply
int a = del("Foo");
It's this last usage that makes it look like a function pointer ('del' is pointing to the SomeFunc function), and it's typesafe because it only takes and returns the types defined (the rules are a bit more complicated than this).
You also now have other ways of calling the delegate notable anonymous methods and lambdas but that's beyond the scope of this
A lot of this happens with compiler magic, for example turning the delegate definition into a class definition and turning the call to the method into a call to Invoke.
HTH
Here's an excellent article about delegates and later on discusses Lambda expressions highlighting the relationship between them.
Hope this helps.
精彩评论