Is there a way to define C# strongly-typed aliases of existing primitive types like `string` or `int`?

前端 未结 7 1213
忘掉有多难
忘掉有多难 2021-02-18 18:52

Perhaps I am demonstrating my ignorance of some oft-used feautre of C# or the .NET framework, but I would like to know if there is a natively-supported way to create a type alia

7条回答
  •  逝去的感伤
    2021-02-18 19:27

    I made this class to cover identical needs. This one is for the type "int" (I also have one for "string"):

    public class NamedInt : IComparable, IEquatable
    {
        internal int Value { get; }
    
        protected NamedInt() { }
        protected NamedInt(int val) { Value = val; }
        protected NamedInt(string val) { Value = Convert.ToInt32(val); }
    
        public static implicit operator int (NamedInt val) { return val.Value; }
    
        public static bool operator ==(NamedInt a, int b) { return a?.Value == b; }
        public static bool operator ==(NamedInt a, NamedInt b) { return a?.Value == b?.Value; }
        public static bool operator !=(NamedInt a, int b) { return !(a==b); }
        public static bool operator !=(NamedInt a, NamedInt b) { return !(a==b); }
    
        public bool Equals(int other) { return Equals(new NamedInt(other)); }
        public override bool Equals(object other) {
            if ((other.GetType() != GetType() && other.GetType() != typeof(string))) return false;
            return Equals(new NamedInt(other.ToString()));
        }
        private bool Equals(NamedInt other) {
            if (ReferenceEquals(null, other)) return false;
            if (ReferenceEquals(this, other)) return true;
            return Equals(Value, other.Value);
        }
    
        public int CompareTo(int other) { return Value - other; }
        public int CompareTo(NamedInt other) { return Value - other.Value; }
    
        public override int GetHashCode() { return Value.GetHashCode(); }
    
        public override string ToString() { return Value.ToString(); }
    }
    

    And to consume it in your case:

    public class MyStronglyTypedInt: NamedInt {
        public MyStronglyTypedInt(int value) : base(value) {
            // Your validation can go here
        }
        public static implicit operator MyStronglyTypedInt(int value) { 
            return new MyStronglyTypedInt(value);
        }
    
        public bool Validate() {
            // Your validation can go here
        }
    }
    

    If you need to be able to serialize it (Newtonsoft.Json), let me know and I'll add the code.

提交回复
热议问题