我想出了這個,不是最優雅的解決方案不知道如果我想借此生產
t.Add(1, 1) // for dictionaries
and t.Add(1) // for Lists
將是巨大的。 它從使用Func <>傳入的查詢中讀取SQL Server表,並且傳入的Action對象作爲參數用於將對象添加到集合。
public C Read<C, T>(Func<SqlConnection, SqlDataReader> func, Action<C, T> a)
where C : ICollection, new()
where T : EntityBase, new()
{
C objects = new C();
using (SqlConnection connection = GetConnection())
{
using (SqlDataReader reader = func(connection))
{
while (reader.Read())
{
T obj = new T();
obj.PopulateFromReader(reader);
a(objects, obj);
}
}
}
return objects;
}
這樣調用:
Dictionary<Guid, DeliveryMoment> dic = _dalBO.Read<Dictionary<Guid, DeliveryMoment>, DeliveryMoment>(connection => { return CmdFactory.ReadDeliveryMoments(connection); }, (d, o) => { d.Add(o.DeliveryMomentId, o); });
你覺得呢?太陰暗或可以接受?
你如何*實際*得到鍵和值?如果你填寫一個清單,你會丟棄鍵還是值?或者用鍵/值對填充它?提供一個序列並允許調用者調用「ToDictionary」或「ToList」不是更簡單嗎?目前這個問題太模糊,不能回答,說實話。 –
你不能使用'Add',因爲它不是'ICollection'接口的一部分。 –