我想实现抽象工厂模式以最大化代码效率来读取我的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