C# 摆脱泛型类型参数:可能吗?
考虑以下类似DAL的代码:C# 摆脱泛型类型参数:可能吗?,c#,.net,generics,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>,
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;
}
mDealerTypes=Read(
()=>{return-DALFactory.Instance.ReadDealerTypes(cn);},
(c,o)=>c.Add(o.DealerTypeKey,o));
mccountries=读取(
()=>{return-DALFactory.Instance.ReadDealerTypes(cn);},
(c,o)=>c.Add(o.Code,o));
私有C读取(函数,操作a)
其中C:ICollection,new()
其中T:EntityBase,new()
{
C对象=新的C();
使用(IDataReader reader=func(连接))
{
while(reader.Read())
{
T obj=新的T();
对象初始化(读取器);
a(对象,obj);
}
}
归还物品;
}
为了可读性,我想以某种方式对此进行更改,以便存储在集合中的对象不会在Read的type参数列表中重复两次
mccountries=Read(
()=>{return-DALFactory.Instance.ReadDealerTypes(cn);},
(c,o)=>c.Add(o.Code,o));
但如何重写阅读呢?这可能吗
私人的??读取(函数函数,动作a)
创建一个简单的包装方法(或扩展方法)
公共字典ReadEx(…),其中T2:EntityBase
{
返回读取(…)
}
就我个人而言,我发现总是从Dal方法返回一个平面枚举或集合,然后让调用方通过调用.ToDictionary(o=>o.DealerTypeKey)来构建字典更具可读性。
mCountries = Read<Dictionary<string, Country>>(
() => { return DALFactory.Instance.ReadDealerTypes(cn); },
(c, o) => c.Add(o.Code, o));
public Dictionary<T1, T2> ReadEx<T1, T2>(...) where T2 : EntityBase
{
return Read<Dictionary<T1, T2>, T2>(...)
}