调用/创建委托 [英] Invoking/Creating Delegate
问题描述
大家好,
我注意到有两种方法可以调用/创建委托
there are 2 ways I've noticed I can invoke/create delegate either
MrDel MyDelegate = new MrDel(Mathmetics.Method);
或
MrDel MyDelegate = Mathmetics.Method;
所以我的问题是这两种方式之间有什么区别?如果第二个的键入要短得多,并且它们似乎在做同样的事情,为什么还要使用第一个?通过阅读一些教程,我发现ppl是使用第一种方法还是第二种方法,但是它们并没有真正解释为什么.谢谢.您能帮我说清楚吗?或指出我可以在哪里读到它.
So my question is whats the difference between those 2 ways? Why Would I need to use first one if second one is much shorter to type and they seemingly doing the same thing? By going through some of the tutorials I'm seeing ppl either using first way or second way but they don't realy explaining WHY. Could you help me make it clear or point out where I can read about it, thank you.
完整代码:
class Program
{
public delegate void MrDel(int arg, ThingsToDo e);
static void Main(string[] args)
{
MrDel MyDelegate = new MrDel(Mathmetics.Method);
//MrDel MyDelegate = Mathmetics.Method;
Method(MyDelegate);
Console.Read();
}
推荐答案
它们是相同的-第二个是首先是语法糖.为了确认我查看了为两者生成的IL,它们是相同的:
They are the same - the second is Syntactic Sugar for the first. To confirm I looked at the IL generated for both, and they are identical:
IL_0001: ldarg.0
IL_0002: ldftn UserQuery.Method
IL_0008: newobj UserQuery+MrDel..ctor
IL_000D: stloc.0 // MyDelegate
Method:
IL_0000: nop
IL_0001: ret
MrDel.Invoke:
MrDel.BeginInvoke:
MrDel.EndInvoke:
MrDel..ctor:
这篇关于调用/创建委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!