类中的 C# 公共枚举
我有一个包含公共枚举的类的程序,如下所示:
public class Card
{
public enum card_suits
{
Clubs,
Hearts,
Spades,
Diamonds
}
...
我想在项目的其他地方使用它,但如果不使用 Card.card_suit 就无法做到这一点。有谁知道 C# 中是否有一种方法可以声明它,以便我能够
card_suits suit;
在不引用它所在的类的情况下进行声明?
I have a program with a class that contains a public enum, as follows:
public class Card
{
public enum card_suits
{
Clubs,
Hearts,
Spades,
Diamonds
}
...
I want to use this elsewhere in my project, but can't do that without using Card.card_suit. Does anyone know if there's a way in C# to declare this so that I am able to declare
card_suits suit;
Without referencing the class that it's in?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
目前,您的
enum
嵌套在您的Card
类中。您所要做的就是将enum
的定义移出类:指定:
名称从
card_suits
更改为建议使用 CardSuit
是因为 Microsoft 指南建议枚举使用 Pascal Case,并且在这种情况下单数形式更具描述性(复数形式表明您通过 OR 运算来存储多个枚举值)。Currently, your
enum
is nested inside of yourCard
class. All you have to do is move the definition of theenum
out of the class:To Specify:
The name change from
card_suits
toCardSuit
was suggested because Microsoft guidelines suggest Pascal Case for Enumerations and the singular form is more descriptive in this case (as a plural would suggest that you're storing multiple enumeration values by ORing them together).您需要在类之外定义枚举。
话虽这么说,您可能还想考虑使用 枚举的标准命名指南,这将是 CardSuit 而不是 card_suits,因为建议使用 Pascal 大小写,并且枚举没有用 FlagsAttribute,建议在单个变量中使用多个值是合适的。
You need to define the enum outside of the class.
That being said, you may also want to consider using the standard naming guidelines for Enums, which would be CardSuit instead of card_suits, since Pascal Casing is suggested, and the enum is not marked with the FlagsAttribute, suggesting multiple values are appropriate in a single variable.
只需在类的边界之外声明枚举即可。像这样:
记住枚举是一种类型。如果枚举要被其他类使用,您也可以考虑将枚举放在它自己的文件中。 (您正在编写纸牌游戏,而花色是纸牌的一个非常重要的属性,在结构良好的代码中,需要由许多类访问。)
Just declare the enum outside the bounds of the class. Like this:
Remember that an enum is a type. You might also consider putting the enum in its own file if it's going to be used by other classes. (You're programming a card game and the suit is a very important attribute of the card that, in well-structured code, will need to be accessible by a number of classes.)
只需在类定义之外声明它即可。
如果你的命名空间的名称是 X,你将能够通过 X.card_suit 访问枚举的值。
如果你没有为此枚举定义命名空间,只需通过 card_suit.Clubs 等调用它们。
Just declare it outside class definition.
If your namespace's name is X, you will be able to access the enum's values by X.card_suit
If you have not defined a namespace for this enum, just call them by card_suit.Clubs etc.