如何在 C# 中全局访问枚举类型?
这可能是一个愚蠢的问题,但我似乎无法做到。我想在一个类中设置一些枚举,如下所示:
public enum Direction { north, east, south, west };
然后让所有类都可以访问该枚举类型,以便其他类可以例如具有:
Direction dir = north;
并能够在类之间传递枚举类型:
public void changeDirection(Direction direction) {
dir = direction;
}
我认为将枚举设置为public 会使这自动成为可能,但它似乎在我声明枚举的类之外不可见。
This is probably a stupid question, but I can't seem to do it. I want to set up some enums in one class like this:
public enum Direction { north, east, south, west };
Then have that enum type accessible to all classes so that some other class could for instance have:
Direction dir = north;
and be able to pass the enum type between classes:
public void changeDirection(Direction direction) {
dir = direction;
}
I thought that setting the enum to public would make this automatically possible, but it doesn't seem to be visible outside of the class I declared the enum in.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以做两件事之一。
1- 将枚举的声明移到类之外
今天您可能有类似这样的内容
,它将更改为
2- 使用类名称引用枚举< br>
例如。
其中
ClassName
是您在其中声明枚举的类的名称。You can do one of two things.
1- Move the declaration of the enum outside of the class
Today you probably have something like this
Which will change to
2- Reference the enum using the class name
Eg.
Where
ClassName
is the name of the class that you declared the enum in.像类一样在命名空间的范围内声明枚举,但不要在类中声明枚举:
如果在类的范围内声明枚举,则也将此类声明为公共:
用法:
Declare enum in the scope of a namespace like a class but not into a class:
In case enum is declared in the scope of a class, you have make this class public too:
Usage:
它是公共的,但在类内定义枚举使其成为该类的内部类型。例如:
为了从
MyNamespace
命名空间中的另一个类访问此枚举,您必须将其引用为Foo.MyEnum
,而不仅仅是MyEnum
>。如果您想简单地将其引用为MyEnum
,请在命名空间内而不是在类内声明它:It's public, but defining an enum inside a class makes it an inner type of that class. For instance:
In order to access this enum from another class in the
MyNamespace
namespace, you have to reference it asFoo.MyEnum
, not justMyEnum
. If you want to reference it as simplyMyEnum
, declare it just inside the namespace rather than inside the class:将
enum
定义放在Program.cs
文件内部,但在Program
类外部。这将使enum
类型可以全局访问,而无需引用类名。然后,您可以在同一命名空间内的任何类中任何访问它,而无需指定类名,如下所示:
Put the
enum
definition inside of theProgram.cs
file, but outside of theProgram
class. This will make theenum
type globally accessible without having to reference the class name.Then you can access it anywhere in any class within the same namespace without the need to specify the class name like this: