我正在编写一个自定义的通用 VectorN 类,其中 T:struct、IFormattable、IComparable、IConvertible。我可以通过 this[int index] 访问向量的索引值。所以在一个循环中,我执行这段代码来制作 VectorN.One:
r[i] = (T)Convert.ChangeType(1, typeof(T));
它与标准数字(例如 int、decimal 等)完美配合,但是当我编写自定义 struct uHalfByte 进行测试时,它给出了错误:
从“System.Int32”到“uHalfByte”的无效转换。
这是uHalfByte的脚本:
struct uHalfByte : IFormattable, IComparable<uHalfByte>, IConvertible
{
private byte val;
public byte Val
{
get { return (byte)(val & 0xF); }
set { val = (byte)(value & 0xF); }
}
public uHalfByte(byte val)
{
this.val = (byte)(val & 0xF);
}
public string ToString(string format, IFormatProvider formatProvider)
{
if (formatProvider == null) formatProvider = System.Globalization.CultureInfo.CurrentCulture;
if (string.IsNullOrEmpty(format)) format = "G";
string s = "";
for (int i = 0; i < 4; i++) s += ((Val >> i) & 1).ToString(format,formatProvider);
return s;
}
public int CompareTo(uHalfByte other)
{
return this.Val - other.Val;
}
public TypeCode GetTypeCode()
{
return TypeCode.Byte;
}
public bool ToBoolean(IFormatProvider provider)
{
return val!=0;
}
public char ToChar(IFormatProvider provider)
{
return (char)val;
}
public sbyte ToSByte(IFormatProvider provider)
{
return (sbyte)val;
}
public byte ToByte(IFormatProvider provider)
{
return (byte)val;
}
public short ToInt16(IFormatProvider provider)
{
return (short)val;
}
public ushort ToUInt16(IFormatProvider provider)
{
return (ushort)val;
}
public int ToInt32(IFormatProvider provider)
{
return (int)val;
}
public uint ToUInt32(IFormatProvider provider)
{
return (uint)val;
}
public long ToInt64(IFormatProvider provider)
{
return (long)val;
}
public ulong ToUInt64(IFormatProvider provider)
{
return (ulong)val;
}
public float ToSingle(IFormatProvider provider)
{
return (float)val;
}
public double ToDouble(IFormatProvider provider)
{
return (double)val;
}
public decimal ToDecimal(IFormatProvider provider)
{
return (decimal)val;
}
public DateTime ToDateTime(IFormatProvider provider)
{
return new DateTime(val);
}
public string ToString(IFormatProvider provider)
{
return ToString("", provider);
}
public object ToType(Type conversionType, IFormatProvider provider)
{
return Convert.ChangeType(val, conversionType);
}
public static explicit operator uHalfByte(int val)
{
return new uHalfByte((byte)val);
}
}
我在 uHalfByte 中做错了什么还是不可能?