c# deriving from int32

后端 未结 5 1346
滥情空心
滥情空心 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 01:55

    You can't derive from Int32, but you can specify implicit conversions, which might give you the behaviour you need:

    public struct RoomId
    {
        private int _Value;
    
        public static implicit operator RoomId(int value)
        {
            return new RoomId { _Value = value };
        }
    
        public static implicit operator int(RoomId value)
        {
            return value._Value;
        }
    }
    
    // ...
    
    RoomId id = 42;
    
    Console.WriteLine(id == 41);    // False
    Console.WriteLine(id == 42);    // True
    Console.WriteLine(id < 42);     // False
    Console.WriteLine(id > 41);     // True
    Console.WriteLine(id * 2);      // 84
    

提交回复
热议问题