我有一个字节数据数组,但是这个数组可以包含任何无符号数字(byte/ushort/uint/ulong)作为字节。一般从字节数组中检索不同的数字数据类型
这样做的问题是将数据再次检索到所需的类型:我希望将数据转换回处理程序类中所需的数据类型,而不是再次请求数据的数据类型(可以将返回的数据代表该值的字节数组)。
此外,ref或out变量,虽然是一种解决方案,是一个麻烦作为成员我指定不一定我返回类型(读显式枚举):
public enum SomeEnum : ulong
{
// ...
}
的功能我现在有:
/// <summary>
/// Get data (byte)
/// </summary>
public byte GetDataByte(byte dataIndex)
{
return this.Data[dataIndex];
}
/// <summary>
/// Get data (ushort)
/// </summary>
public ushort GetDataUshort(byte startingDataIndex)
{
ushort output = 0;
for (byte i = startingDataIndex; i < this.Data.Length && i < sizeof(ushort); i++)
{
output |= (ushort)(this.Data[i] << (i * 8));
}
return output;
}
/// <summary>
/// Get data (uint)
/// </summary>
public uint GetDataUint(byte startingDataIndex)
{
uint output = 0;
for (byte i = startingDataIndex; i < this.Data.Length && i < sizeof(uint); i++)
{
output |= ((uint)this.Data[i] << (i * 8));
}
return output;
}
/// <summary>
/// Get data (ulong)
/// </summary>
public ulong GetDataUlong(byte startingDataIndex)
{
ulong output = 0;
for (byte i = startingDataIndex; i < this.Data.Length && i < sizeof(ulong); i++)
{
output |= ((ulong)this.Data[i] << (i * 8));
}
return output;
}
这可以合并成一个函数,我会怎么做呢?像
SomeEnum member = (SomeEnum)GetData<ulong>(dataIndex);
但
GetData<byte>(0);
public T GetData<T>(byte startingDataIndex) // T would be byte during runtime
{
return this.Data[dataIndex]; // Compiler: Er, T? Byte? what?
}
或
/// <summary>
/// Get data (T)
/// </summary>
public T GetData<T>(byte startingDataIndex)
{
T output = 0; // Compiler: derp, this isn't an integer.
for (byte i = startingDataIndex; i < this.Data.Length && i < System.Runtime.InteropServices.Marshal.SizeOf(typeof(T)); i++)
{
output |= (T)(this.Data[i] << (i * 8)); // Compiler: nor is this!
}
return output;
}
还是我真是再好不过了,留下作为单独的功能和维护它们呢?
我喜欢这种设计方法,但它不会编译为'ReadInt(startIndex);'会返回一个int(不是T)和'ReadByte(startIndex);'会返回一个字节(不是T)。因为编译器不知道如何将int或byte转换为T,所以不能将其转换为T. – kjhf
等待,重复播放(T)(对象)有效。 :) – kjhf
是的,对不起,我会更新代码。我刚刚从我头顶吹了一些东西。 –