我想實現抽象工廠模式以最大化代碼效率來讀取我的coımmon引用類型。要做到這一點,我有以下實現抽象工廠執行錯誤
,並執行我已經實現了模式如下:
我對RefEntityFactor類代碼:
public class RefEntityFactory<T> : IRefEntityFactory<T> where T : IRefEntity
{
public List<T> Search(string sp_name, int? id, string code, int? statusid)
{
List<T> irefs = new List<T>();
string procName = sp_name;
SqlConnection conn = null;
using (conn = GetConnection())
{
SqlCommand cmd = new SqlCommand(procName, conn);
cmd.CommandType = CommandType.StoredProcedure;
if (id.HasValue)
cmd.Parameters.AddWithValue("@ID", id.Value);
if (!string.IsNullOrEmpty(code) && !string.IsNullOrWhiteSpace(code))
cmd.Parameters.AddWithValue("@CODE", code.Trim());
if (statusid.HasValue)
cmd.Parameters.AddWithValue("@STATUS", statusid.Value);
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
RefEntity refe = new RefEntity();
refe.Id = int.Parse(rd["ID"].ToString());
refe.Code = rd["CODE"].ToString();
refe.Status = short.Parse(rd["STATUS"].ToString());
IRefEntity iref = (IRefEntity)refe;
irefs.Add((T)iref); // Exception will be THROWN HERE!!!!
}
rd.Close();
}
return irefs;
}
}
然後,我實現一個類spesific類型:
爲
public static List<IPaymentType> SearchPaymentTypes(int? id, string code, int? statusid)
{
RefEntityFactory<IPaymentType> fact = new RefEntityFactory<IPaymentType>();
return fact.Search(@"[dbo].[SEARCH_PAYMENTTYPES]", id, code, statusid);
}
但很明顯,當我運行它拋出在哪裏標記爲註釋的行異常的代碼。
如何更正我的實施?
問候。
不應該你的方法返回'List'而不是'List ',你的代碼試圖將'RefEntity'強制轉換爲'T',所以如果'T'比'RefEntity'多派生,那麼它會失敗。你也可以做'IRefEntity iref = new RefEntity();'並完全移除'refe'。 –
2014-12-04 13:34:49
是零異常還是文件未找到異常? – 2014-12-04 13:36:04
@BenRobinson:當我將返回類型轉換爲列表而不是列表時,我無法編寫SearchPaymentTypes方法。返回類型將是我需要返回IPaymentType和list.ForEach(x =>(IPaymentType)x)集合的IRefEntity的集合;不管用。 –
user3021830
2014-12-04 13:45:43