我正在尝试以通用方式使用 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 语句?
最佳答案
除了使用反射(这会很慢),我能想到的你可能更喜欢的唯一选择是构建一个字典:
static object s_lock = new object();
static IDictionary<Type, Func<BinaryReader, dynamic>> s_readers = null;
static T ReadData<T>(string fileName)
{
lock (s_lock)
{
if (s_readers == null)
{
s_readers = new Dictionary<Type, Func<BinaryReader, dynamic>>();
s_readers.Add(typeof(int), r => r.ReadInt32());
s_readers.Add(typeof(string), r => r.ReadString());
// Add more here
}
}
if (!s_readers.ContainsKey(typeof(T))) throw new ArgumentException("Invalid type");
using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
using (var reader = new BinaryReader(fs))
{
return s_readers[typeof(T)](reader);
}
}
您调用它的代码会更清晰,但您仍然必须将每个 Read 函数映射到一个类型。
关于c# - 如何使用BinaryReader Read方法读取动态数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13651757/