如何更正构造函数?

How to correct the constructor?

using System;
using System.Text;
using System.Collections.Generic;

class RGB: IEquatable<RGB> {
  private byte R, G, B;

  public static RGB Red   = new(255, 0, 0);
  public static RGB Green = new(0, 255, 0);
  public static RGB Blue  = new(0, 0, 255);

  public RGB(byte R, byte G, byte B) {
    this.R = R;
    this.G = G;
    this.B = B;
  }

  public RGB(string color_hexcode){
    byte[] red_bytes   = Encoding.UTF8.GetBytes(color_hexcode[1..3]);
    byte[] green_bytes = Encoding.UTF8.GetBytes(color_hexcode[3..5]);
    byte[] blue_bytes  = Encoding.UTF8.GetBytes(color_hexcode[5..]);
    
    this.R = Convert.ToByte(Convert.ToHexString(red_bytes));
    this.G = Convert.ToByte(Convert.ToHexString(green_bytes));
    this.B = Convert.ToByte(Convert.ToHexString(blue_bytes));
  }

  public byte RedValue   { get => this.R; }
  public byte GreenValue { get => this.G; }
  public byte BlueValue  { get => this.B; }

  public bool ContainsRed   { get => this.R != 0  ? true : false; }
  public bool ContainsGreen { get => this.G != 0  ? true : false; }
  public bool ContainsBlue  { get => this.B != 0  ? true : false; }

  public bool Equals(RGB other) {
    return (this.R, this.G, this.B) == (other.R, other.G, other.B);
  }
}

class Program {
  public static void Main (string[] args) {
    RGB Yellow = new("#ffff00");
    Console.WriteLine(Yellow.ContainsBlue);
  }
}

我的代码导致: Unhandled exception. System.OverflowException: Value was either too large or too small for an unsigned byte.public RGB(string color_hexcode)...

我尝试将字符串转换为十六进制字符串,然后将十六进制字符串转换为字节。 #ff 等于十进制数 255。因此 #ffbyte 数据类型的范围内。我不明白这段代码有什么问题。 C# 必须将 #ff 无缝转换为字节。有人知道如何解决吗?

假设你的 color_hexcode 是一个像 #ffeecc 这样的字符串:

  public RGB(string color_hexcode){

    this.R = byte.Parse(color_hexcode[1..3], NumberStyles.HexNumber);
    this.G = byte.Parse(color_hexcode[3..5], NumberStyles.HexNumber);
    this.B = byte.Parse(color_hexcode[5..7], NumberStyles.HexNumber);
  }

至于为什么你的尝试失败了:

  • Encoding.UTF8.GetBytes() 将采用像“ff”这样的字符串和 return 组成这些字符的字节。 f 为 99 或 0x63
  • 这意味着它给你 new byte[] {0x63, 0x63}
  • Convert.ToHexString 这给你 "6363"
  • Convert.ToByte 在“6363”上爆炸了,因为无论你用哪种方式切割它,无论是 6363 还是 0x6363,它都比一个字节大