我正在尝试以通用方式使用 BinaryReader Read 方法。只有在运行时我才知道正在读取的数据类型。
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 语句?