3
我想以通用的方式使用BinaryReader读取方法。只有在运行时我知道正在读取的数据的类型。如何使用BinaryReader读取方法读取动态数据?
public static T ReadData<T>(string fileName)
{
var value = default(T);
using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (var reader = new BinaryReader(fs))
{
if (typeof (T).GetGenericTypeDefinition() == typeof (Int32))
{
value = (dynamic) reader.ReadInt32();
}
if (typeof (T).GetGenericTypeDefinition() == typeof (string))
{
value = (dynamic) reader.ReadString();
}
// More if statements here for other type of data
}
}
return value ;
}
如何避免多个if语句?
那里调用'GetGenericTypeDefinition'的是什么?如果'T'是一个泛型类型,它肯定不是由'System.Int32'或'System.String'构造的,因为它们不是泛型类型定义。另一方面,如果'T' *是*'Int32'或'String','GetGenericTypeDefinition'将在非泛型类型上调用''InvalidOperationException''。 –
此外,这是如何*不*使用泛型的一个很好的例子 - 所有类型支持的重载是一个更好的解决方案,他们使所有手动类型检查与链接'if's过时。 –