代表或代表 [英] Delegate or delegate
本文介绍了代表或代表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在我的一个项目中与代表合作。我知道Delegate是一个类(Syatem.Delegate),委托是一个关键字。但是我无法理解为什么我不能在方法中创建委托类型但是对于Delaget来说它在方法中很好(方法不能在正文中定义类型)
Ex:
Hi,
I am working with delegates in one of my project. I know that Delegate is a class (Syatem.Delegate)and delegate is a keyword for the same. But I am not able to understand why I can not create delegate type in method but for Delaget it goes fine in a method(method can not have types defined in the body)
Ex:
public static void PerformFacade(int gradeInput, int method)
{
MethodInfo mInfo = typeof(CompanyArchFacade).GetMethod("MyMethod");
// works fine
Delegate callMethod = Delegate.CreateDelegate(typeof(selectedOperation), mInfo);
// throws error
delegate callMethod = Delegate.CreateDelegate(typeof(selectedOperation), mInfo);
selectedOperation selOp = (selectedOperation)callMethod;
selOp();
}
请注意。谢谢!
问候,
Divya
Please advise. Thanks !
Regards,
Divya
推荐答案
不,关键字委托
和System.Delegate
不一样,完全没有。
您可能会对C#别名关键字感到困惑。例如,int是System.Int32
的别名。对于代表来说,情况并非如此。
阅读有关这些类型的文档,并查看使用该关键字的所有情况。它并不像你想象的那么微不足道。特别是,不要错过在匿名代表中使用此关键字。请从这里开始:
http:// msdn.microsoft.com/en-us/library/ms173171%28v=vs.110%29.aspx [ ^ ]。
请查看我的过去关于这个主题的答案:
在N#中传递一个带有N参数作为参数的方法 [ ^ ],
代表的额外优势是什么 [ ^ ],
关于代表的混淆 [ ^ ]。
特别是你应该特别注意一件复杂的事情:用delegate
关键字声明一个委托类型。创建委托实例。使用GetType
方法检查委托实例的运行时类型。您会发现这是与委托类型无关的类!
有关解释,请参阅我的文章:动态方法调度程序 [ ^ ]。< br $>
-SA
No, the keyworddelegate
andSystem.Delegate
are not the same, not at all.
You could be confused with the C# alias keywords. For example "int" is an alias forSystem.Int32
. For delegates, this is not the case.
Read the documentation on these type and look through all the cases of using the keyword. It''s not as trivial as you may think. In particular, don''t miss the use of this keyword in anonymous delegates. Please start here:
http://msdn.microsoft.com/en-us/library/ms173171%28v=vs.110%29.aspx[^].
Please see my past answers on the topic:
Pass a method with N params as parameter in C#[^],
What is the Extra Advantage of Delegate[^],
Confusion about delegates[^].
In particular, you should pay special attention for one complicated thing: declare a delegate type with thedelegate
keyword. Create a delegate instance. Check up the runtime type of the delegate instance usingGetType
method. You will find that this is the class which has nothing to do with the delegate type!
For some explanations, please see my article: Dynamic Method Dispatcher[^].
—SA
这篇关于代表或代表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文