简体   繁体   English

为什么我不能在功能级别声明代理?

[英]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.

相关问题 如何在接口中使用默认参数声明委托给函数? - How can I declare delegate to a function with default parameters in an interface? 为什么我不能在接口中放置一个委托? - Why can't I put a delegate in an interface? 当函数可以返回MemoryStream时,为什么我不能声明MemoryStream为空(MemoryStream?)? - Why can't I declare a MemoryStream nullable (MemoryStream?) when a function can return MemoryStream? 使用C#4.0中的匿名函数,为什么我无法定义内联委托 - With anonymous function in C# 4.0 why can't I define a delegate inline 为什么我不能在DelegateCommand的Execute委托中访问实例属性? - Why can't I access instance properties in the Execute delegate of a DelegateCommand? 为什么我不能使用Extension方法隐式地转换Delegate? - Why can't I implicitly cast a Delegate with Extension methods? 为什么我们不能声明var a = new List <string> 在课堂上? - Why can't we declare var a = new List<string> at class level? C# - 无法在方法中声明委托 - C# - Can't declare delegate within a method 为什么我不能在接口中声明公共方法? - Why can't I declare a public method in an interface? 为什么不能为名称空间声明using语句,但是可以在类型之前直接声明名称空间? - Why can't I declare a using statement for a namespace, but can directly declare the namespace before the type?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM