开发者

C# Public Enums in Classes

开发者 https://www.devze.com 2022-12-25 04:36 出处:网络
I have a program with a class that contains a public enum, as follows: public class Card { public enum card_suits

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?


Currently, your enum is nested inside of your Card class. All you have to do is move the definition of the enum out of the class:

// A better name which follows conventions instead of card_suits is
public enum CardSuit
{
    Clubs,
    Hearts,
    Spades,
    Diamonds
}

public class Card
{
}

To Specify:

The name change from card_suits to CardSuit 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).


You need to define the enum outside of the class.

public enum card_suits
{
    Clubs,
    Hearts,
    Spades,
    Diamonds
}

public class Card
{
     // ...

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:

public enum card_suits
{
    Clubs,
    Hearts,
    Spades,
    Diamonds
}

public class Card
{
    ...
}

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.)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号