无法转换类型' T'布尔

时间:2014-09-14 16:38:22

标签: c#

基本上我有这些错误,代码是粗体:

Cannot convert type 'T' to bool
Cannot convert type 'T' to string x2
Cannot convert type 'T' to byte[]
Cannot convert type 'T' to byte

我一直在寻找谷歌,似乎无法找到解决方法,提前谢谢

public void Append<T>(T value, bool littleEndian = false)
    {
        try
        {
            System.Type t = typeof(T);
            if (!this.IsValidType(t))
            {
                throw new Exception("msg_t.AppendMessage: Invalid type!");
            }
            if (t == typeof(bool))
            {
                ((XDevkit.IXboxConsole) this.XboxConsole).WriteInt32(this.DataBuffer + this.MessageLength, ***((bool) value)*** ? 1 : 0);
                this.MessageLength += 4;
            }
            else if (t == typeof(string))
            {
                ((XDevkit.IXboxConsole) this.XboxConsole).WriteString(this.DataBuffer + this.MessageLength, ***(string) value)***;
                this.MessageLength += (uint) Encoding.UTF8.GetBytes(***(string) value)***.Length;
            }
            else if (t == typeof(byte[]))
            {
                byte[] data = ***(byte[]) value***;
                ((XDevkit.IXboxConsole) this.XboxConsole).SetMemory(this.DataBuffer + this.MessageLength, data);
                this.MessageLength += (uint) data.Length;
            }
            else if (t == typeof(byte))
            {
                ((XDevkit.IXboxConsole) this.XboxConsole).WriteByte(this.DataBuffer + this.MessageLength, ***(byte) value***);
                this.MessageLength++;
            }
            else
            {
                byte[] array = (byte[]) typeof(BitConverter).GetMethod("GetBytes", new System.Type[] { value.GetType() }).Invoke(null, new object[] { value });
                if (!littleEndian)
                {
                    Array.Reverse(array);
                }
                ((XDevkit.IXboxConsole) this.XboxConsole).SetMemory(this.DataBuffer + this.MessageLength, array);
                this.MessageLength += (uint) array.Length;
            }
            this.UpdateOverflowedBoolean();
        }
        catch
        {
            if (MessageBox.Show("Error when writing stats!", "GHOSTS", MessageBoxButtons.RetryCancel, MessageBoxIcon.Hand) == DialogResult.Retry)
            {
                this.Append<T>(value, littleEndian);
            }
        }
    }

1 个答案:

答案 0 :(得分:10)

不幸的是,C#中的泛型转换规则不允许这样做,但您可以通过object。例如:

byte[] data = (byte[]) (object) value;

但是,您可能会考虑是否真的适合作为通用方法...它不像是应对所有类型,或者对所有类型都做同样的事情它 接受。

我还强烈建议提取在所有成功案例中使用的表达式((XDevkit.IXboxConsole) this.XboxConsole)