C# Char from Int used as String - the real equivalent of VB Chr()

前端 未结 4 1705
故里飘歌
故里飘歌 2020-12-17 18:20

I am trying to find a clear answer to my question and it is not a duplicate of any other questions on the site. I have read many posts and related questions

4条回答
  •  Happy的楠姐
    2020-12-17 19:20

    Just to simplify the syntax. The following AChar class handles the conversions.

    string A = (AChar)65;
    Console.WriteLine(A); // output is "A"
    

    The following class represents a character and defines conversions from ASCII code page:

    struct AChar
    {
        public static implicit operator AChar(char value) => new AChar { Value = value };
    
        public static explicit operator AChar(string value)
        {
            if (string.IsNullOrEmpty(value))
                return '\x0000';
    
            if (value.Length > 1)
                throw new InvalidCastException("String contains more than 1 character.");
    
            return value[0];
        }
    
        public static explicit operator AChar(long value)
        {
            if(value < 0 || value > 0xFF)
                throw new InvalidCastException("Char code is out of ASCII range.");
    
            return (AChar)Encoding.ASCII.GetString(new[] { (byte)value });
        }
    
        public static implicit operator AChar(byte value) => (AChar)(long)value;
        public static explicit operator AChar(int value) => (AChar)(long)value;
    
        public static implicit operator char(AChar aChar) => aChar.Value;
        public static implicit operator string(AChar aChar) => aChar.Value.ToString();
    
        public static bool operator==(AChar left, AChar right) =>
            left.Value == right.Value;
    
        public static bool operator!=(AChar left, AChar right) =>
            left.Value != right.Value;
    
        public static bool operator >(AChar left, AChar right) =>
            left.Value > right.Value;
    
        public static bool operator >=(AChar left, AChar right) =>
            left.Value >= right.Value;
    
        public static bool operator <(AChar left, AChar right) =>
            left.Value < right.Value;
    
        public static bool operator <=(AChar left, AChar right) =>
            left.Value <= right.Value;
    
        public override string ToString() => this;
    
        public override int GetHashCode() =>    
            Value.GetHashCode();
    
        public override bool Equals(object obj) =>
            obj is AChar && ((AChar)obj).Value == Value;
    
        char Value { get; set; }
    }
    

    Convert you character code to AChar first, it is compatible with char and string of C#.

提交回复
热议问题