1 回答
TA贡献1829条经验 获得超6个赞
您可以创建一个依赖于 的泛型类型的泛型方法<T>,处理读取,将值装箱并最终返回它。例如:
public static Object GetValue<T>(BinaryReader br) {
switch (Type.GetTypeCode(typeof(T)))
{
case TypeCode.Boolean: { return br.ReadBoolean(); }
case TypeCode.Byte: { return br.ReadByte(); }
case TypeCode.Char: { return br.ReadChar(); }
case TypeCode.Decimal: { return br.ReadDecimal(); }
case TypeCode.Double: { return br.ReadDouble(); }
case TypeCode.Int16: { return br.ReadInt16(); }
case TypeCode.Int32: { return br.ReadInt32(); }
case TypeCode.Int64: { return br.ReadUInt64(); }
// Keep on going for other types
default: { return br.Read(); }
}
}
这是一个完整的例子
public class Vector3D<T>
{
public T X { get; set; }
public T Y { get; set; }
public T Z { get; set; }
private readonly String filePath;
public Vector3D(String filePath) {
this.filePath = filePath;
if (File.Exists(filePath))
{
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) {
using(BinaryReader br = new BinaryReader(fs))
{
X = (T) GetValue<T>(br);
Y = (T) GetValue<T>(br);
Z = (T) GetValue<T>(br);
}
}
}
}
public static Object GetValue<T>(BinaryReader br) {
switch (Type.GetTypeCode(typeof(T)))
{
case TypeCode.Boolean: { return br.ReadBoolean(); }
case TypeCode.Byte: { return br.ReadByte(); }
case TypeCode.Char: { return br.ReadChar(); }
case TypeCode.Decimal: { return br.ReadDecimal(); }
case TypeCode.Double: { return br.ReadDouble(); }
case TypeCode.Int16: { return br.ReadInt16(); }
case TypeCode.Int32: { return br.ReadInt32(); }
case TypeCode.Int64: { return br.ReadUInt64(); }
default: { return br.Read(); }
}
}
}
您还可以为此创建扩展方法:
public static class BinaryReaderExtensions
{
public static Object GetValue(this BinaryReader br, Type type)
{
switch (Type.GetTypeCode(type))
{
case TypeCode.Boolean: { return br.ReadBoolean(); }
case TypeCode.Byte: { return br.ReadByte(); }
case TypeCode.Char: { return br.ReadChar(); }
case TypeCode.Decimal: { return br.ReadDecimal(); }
case TypeCode.Double: { return br.ReadDouble(); }
case TypeCode.Int16: { return br.ReadInt16(); }
case TypeCode.Int32: { return br.ReadInt32(); }
case TypeCode.Int64: { return br.ReadUInt64(); }
default: { return br.Read(); }
}
}
}
}
- 1 回答
- 0 关注
- 106 浏览
添加回答
举报