【发布时间】:2015-07-23 23:04:30
【问题描述】:
我有一个Stream,我想从其中读取数据(作为值类型段)并根据给定类型的大小(声明为泛型)移动位置。
我目前的做法:
public byte ReadUInt8(Stream stream) {
return (byte)stream.ReadByte();
}
public ushort ReadUInt16(Stream stream) {
return (ushort)((ReadUInt8() << 8) | ReadUInt8());
}
...
我想要达到的目标:
public TValue Read<TValue>(Stream stream)
where TValue : struct
{
var bufferSize = Marshal.SizeOf(typeof(TValue));
var buffer = new byte[bufferSize];
if(stream.Read(buffer, 0, bufferSize) == 0)
throw new EndOfStreamException();
return (TValue)buffer; // here's where I'm stuck
// EDIT1: A possible way would be
// return (TValue)(object)buffer;
// but that feels like kicking puppies :/
}
这有可能吗?使用Marshal.SizeOf()(性能方面等)有什么缺点吗?
【问题讨论】:
标签: c# generics types stream buffer