Nested Enum and Property Naming Conflicts

后端 未结 7 828
孤城傲影
孤城傲影 2021-02-06 23:48

There are some related questions here and here, but they didn\'t really give me satisfactory answers. The problem is that enums nested in a class in C# cannot have the same name

7条回答
  •  南方客
    南方客 (楼主)
    2021-02-07 00:21

    Wrapping the enum in a struct was well suited for my particular case b/c there was other data at play (the int Value, which is also a value type).

    public class Record
    {
        public enum DurationUnit { Minutes, Hours }
    
        public struct DurationStruct
        {
            public readonly int Value;
            public readonly DurationUnit Unit;
    
            public DurationStruct(int value, DurationUnit unit)
            {
                Value = value;
                Unit = unit;
            }
        }
        public DurationStruct Duration; //{get; set;} -can't return a ref to a val type (in C#)
    
        public void Init()
        {   
            // initialize struct (not really "new" like a ref type)
            // -helpful syntax if DurationStruct ever graduated/ascended to class
            Duration = new DurationStruct(1, DurationUnit.Hours);
        }
    }    
    

    So for the Card class above, it would be something like the following

    public class Card
    {
        public enum Suit { Clubs, Diamonds, Spades, Hearts }
        public enum Rank { Two, Three, ...  King, Ace }
    
        public struct CardStruct
        {
            public Card.Suit Suit { get; private set; }
            public Card.Rank Rank { get; private set; }
        }
    
        //public CardStruct Card {get; set;} -can't be same as enclosing class either
        public CardStruct Identity {get; set;}
    
        public int Value
        {
            get    
            {
                //switch((Suit)Card.Suit)
                switch((Suit)Identity.Suit)
                {
                    //case Suit.Hearts:   return Card.Rank + 0*14;
                    case Suit.Hearts:   return Identity.Rank + 0*14;
                    case Suit.Clubs:    return Identity.Rank + 1*14;
                    case Suit.Diamonds: return Identity.Rank + 2*14;
                    case Suit.Spades:   return Identity.Rank + 3*14;                
                }
            }
        }
    }
    

提交回复
热议问题