我有一个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()
(性能明智等)有什么缺点吗?
答案 0 :(得分:1)
NotFoundHttpException
是的,你刚刚改变了问题。从没有return (TValue)buffer; // here's where I'm stuck
到std库中没有Stream.Read<T>()
而且你必须像Convert<T>(byte[])
那样称之为Read<int>()
,因此没有BinaryReader.ReadInt32()
现在,当您想要从另一个泛型类/方法中使用它时,Read<T>()
语法很有用,但是对于实现,您也可以将它映射到BinaryReader调用。我担心会需要拳击:
obcject result = null;
if (typeof(TValue) == typeof(int))
result = reader.ReadInt32();
else if (typeof(TValue) == typeof(double))
result = reader.ReadDouble();
else ...
return (TValue) result;