主方法中的枚举声明 [英] Enum declaration inside main method

查看:83
本文介绍了主方法中的枚举声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





为什么enum的声明必须在main方法之外?

解决方案

因为枚举基本上是一种类型;它必须在命名空间或封闭类中声明。

你不能在方法中定义类型。


因为你不能声明任何类型 - 方法中的类,结构或枚举:它们是类/结构的本地或命名空间的全局。该语言不允许类,结构或枚举在方法的本地。



如果你考虑它是有道理的 - 如果可以的话,你会减少你需要将方法重构为单独函数的范围:子方法无法访问在另一个方法体内声明的枚举。


Enum是一个特殊的高级输入C#;与Classes和Structs一样,它可以在Namespace中定义,也可以在Class或Struct中定义。然后,命名空间中的枚举可用于命名空间中的所有类或结构。



但是,请注意,您无法在Struct中定义枚举;但是,你可以在Struct中有一个Type Enum变量。



你不能在方法中定义Class,Enum或Struct;这就是C#语言的实现方式。您可以将Enum视为创建Application结构的声明方面的一部分,而您可能会将Methods和EventHandlers视为Application结构的动态部分的一部分。



Enum将一组整数类型组合在一起;你可能会认为Enum是一组有序的命名常量。



好​​的阅读Enums:



MSDN:[ ^ ]。



C#语言定义:从这里下载.pdf文件:[ ^ ]。



CodeProject:[ ^ ],以及丰富的CP资源: [ ^ ]。

hi ,

why is the declaration of enum must be outside main method ?

解决方案

Because an enum is a basically a type; it has to be declared in a namespace, or in an enclosing class.
You cannot define types in methods.


Because you can't declare any type - class, struct or enum within a method: they are either local to the class / struct or global to the namespace. The language does not allow for classes, structs or enums to be local to a method.

It makes sense if you think about it - if you could, you would reduce the amount of scope you have to refactor your methods into separate functions: the "sub methods" could not access the enum declared within the body of the other method.


An Enum is a special "high-level" Type in C#; like Classes and Structs it can be defined either within a Namespace, or inside a Class or Struct. Enums in a Namespace are, then, available to all Classes, or Structs, in the Namespace.

Note, however, that you cannot define an Enum within a Struct; however, you can have a variable of Type Enum in a Struct.

You cannot define a Class, Enum, or Struct inside a method; that's just the way the C# language is implemented. You can think of an Enum as part of the declarative aspect of creating your Application structure, while you might think of Methods, and EventHandlers, as being part of the dynamic part of Application structure.

An Enum groups together a set of integral Types; you might think of an Enum as a ordered set of named Constants.

Good reading on Enums:

MSDN: [^].

C# Language Definition: download .pdf file from here: [^].

CodeProject: [^], and a wealth of CP resources here: [^].


这篇关于主方法中的枚举声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆