c# deriving from int32

后端 未结 5 1353
滥情空心
滥情空心 2020-12-31 01:38

i have several classes with members called \'Id\'. Originally i wanted to store these as ints, but i would like some layer of protection, to make sure i don\'t accidentally

5条回答
  •  清歌不尽
    2020-12-31 02:15

    If I understand correctly, the only operation you really need is comparison for equality. You can create a RoomId class (or struct, whichever suits you)

    class RoomId
    {
        private int Value {get; set;}
    
        public RoomId(int value)
        {
            this.Value = value;
        }
    
        public bool Equals(RoomId other)
        {
            return this.Value == other.Value;
        }
    }
    
    RoomId room1 = new RoomId(1);
    RoomId room2 = new RoomId(2);
    
    // To compare for equality
    bool isItTheSameRoom = room1.Equals(room2);
    // Or if you have overloaded the equality operator (==)
    bool isItTheSameRoom = room1 == room2;
    

    You can implement IEquatable, overload the equality and inequality operators if you want. If you need persistence, you could implement the ISerializable interface to make sure that the integer value only "escapes" the class if it is really needed.

提交回复
热议问题