3

我正在尝试以通用方式使用 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 语句?

4

1 回答 1

1

除了使用反射(这会很慢)之外,我能想到的你可能更喜欢的唯一选择是构建一个字典:

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 函数映射到一个类型。

于 2012-11-30T19:36:34.223 回答