简体   繁体   中英

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#. 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. Why?

If matters this is the code: 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. 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! It will save you from having declarations everywhere.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM