摆脱泛型类型的论点:这可能吗?

时间:2013-12-12 07:47:38

标签: c# .net generics

考虑这个DAL代码:

mDealerTypes = Read<Dictionary<string, DealerType>, DealerType>(
() => { return DALFactory.Instance.ReadDealerTypes(cn); },
(c, o) => c.Add(o.DealerTypeKey, o));

mCountries = Read<Dictionary<string, Country>, Country>(
() => { return DALFactory.Instance.ReadDealerTypes(cn); },
(c, o) => c.Add(o.Code, o));

        private C Read<C, T>(Func<SqlConnection, IDataReader> func, Action<C, T> a)
            where C : ICollection, new()
            where T : EntityBase, new()
        {
            C objects = new C();

            using (IDataReader reader = func(connection))
            {
                while (reader.Read())
                {
                    T obj = new T();
                    obj.Init(reader);
                    a(objects, obj);
                }
            }

            return objects;
        }

为了便于阅读,我想以某种方式改变这一点,以便存储在集合中的对象不会在Read&lt;&gt;的类型参数列表中重复两次。

mCountries = Read<Dictionary<string, Country>>(
() => { return DALFactory.Instance.ReadDealerTypes(cn); },
(c, o) => c.Add(o.Code, o));

但如何重写Read&lt;&gt;然后?这甚至可能吗?

  私人?阅读(Func func,Action a)

1 个答案:

答案 0 :(得分:1)

创建一个简单的包装器方法(或扩展方法)

public Dictionary<T1, T2> ReadEx<T1, T2>(...) where T2 : EntityBase
{
    return Read<Dictionary<T1, T2>, T2>(...)
}