[英]Why I can`t declare a Delegate at function level?
Sorry if this question is too simple or easy. 对不起,如果这个问题过于简单或容易。
I just started studying Delegates using C#. 我刚开始使用C#学习代表。 When I tried to declare one inside a function I got design time errors, but when I declare the same Delegate at class level, it works fine.
当我试图在函数内声明一个时,我得到了设计时错误,但是当我在类级别声明相同的Delegate时,它工作正常。 Why?
为什么?
If matters this is the code: delegate void Test();
如果这是代码:
delegate void Test();
AFAIK, declaring a delegate like that (in C#, which I assume is the language you are using) is declaring a new type. AFAIK,声明一个这样的代表(在C#中,我假设是你正在使用的语言)声明一个新类型。 Just as you cannot declare classes, structs, or interfaces in a method, you cannot declare this type.
正如您无法在方法中声明类,结构或接口一样,您也无法声明此类型。
Edit: If you're just learning delegates, and the language is indeed c#, consider using the Func templated delegate! 编辑:如果您只是学习代理,并且语言确实是c#,请考虑使用Func模板化委托! It will save you from having declarations everywhere.
它将使您免于在任何地方声明。
http://msdn.microsoft.com/en-us/library/bb549151.aspx http://msdn.microsoft.com/en-us/library/bb549151.aspx
Defining a delegate within a function would essentially be declaring a function within a function. 在函数内定义委托主要是在函数内声明一个函数。 The intention of delegates is to pass them between functions/methods, so they are only useful when declared at the class level.
委托的意图是在函数/方法之间传递它们,因此它们仅在类级别声明时才有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.