问题描述
我有一个 Stream
,我想从中读取数据(作为值类型段)并根据给定类型的大小移动位置(声明为
我目前的做法是:
pre code public byte ReadUInt8( Stream stream){
return(byte)stream.ReadByte(); (ReadUInt8()<< 8)| ReadUInt8());
$ b public ushort ReadUInt16(Stream stream){
return(ushort)
}
...
我想要什么实现:
$ b $ pre $ 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();
返回(TValue)缓冲区; //这里是我被卡住的地方
// EDIT1:可能的方法是
// return(TValue)(object)buffer;
//但是感觉像踢小狗:/
}
这是不知何故可能?是否存在使用 Marshal.SizeOf()
(性能等)的缺点?
return(TValue)buffer; //这里是我被卡住的地方
是的,你刚才转移了问题。从没有 Stream.Read< T>()
没有 Convert< T>(byte [])
在标准库中。
无论如何,你必须将它称为 Read< int>()
,所以不存在直接优势 BinaryReader.ReadInt32()
现在当你想从另一个泛型类/方法中使用它时,读取< 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;
I have a Stream
where I'd like to read data from (as value type segments) and move the position according to the size of the given type (declared as generics).
My current approach:
public byte ReadUInt8(Stream stream) {
return (byte)stream.ReadByte();
}
public ushort ReadUInt16(Stream stream) {
return (ushort)((ReadUInt8() << 8) | ReadUInt8());
}
...
What I'd like to achieve:
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 :/
}
Is this somehow possible? Are there any drawbacks from using Marshal.SizeOf()
(performance-wise etc.)?
return (TValue)buffer; // here's where I'm stuck
Yes, you have just shifted the problem. From not having a Stream.Read<T>()
to not having a Convert<T>(byte[])
in the std library.
And you would have to call it like Read<int>()
anyway so there isn't a direct advantage over BinaryReader.ReadInt32()
Now when you want to use it from another generic class/method, the Read<T>()
syntax is useful but for the implementation you might as well map it to BinaryReader calls. I'm afraid that will require boxing:
obcject result = null;
if (typeof(TValue) == typeof(int))
result = reader.ReadInt32();
else if (typeof(TValue) == typeof(double))
result = reader.ReadDouble();
else ...
return (TValue) result;
这篇关于将字节数组转换为通用值类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!