【发布时间】:2014-09-04 12:47:33
【问题描述】:
我有以下课程。编辑:(我知道这不是一个好习惯):
public class BussinesRuleA
{
private string _connectionString;
public BussinesRuleA(string connectionString)
{
_connectionString = connectionString;
}
public List<persitenceRuleA> getDATA_A(persitenceRuleA perRA, int acao)
{
//EDITED: IT´S MANDATORY make A NEW instance to this DATA ACCESS class
// The connectionString was removed from the constructor
dalRuleA dalRA = new dalRuleA();
List<persitenceRuleA> lst = new List<persitenceRuleA>();
try
{
lst = dalRA.getDATA(perRA, acao);
}
catch (Exception e)
{
throw e;
}
finally
{
dalRA = null;
}
return lst;
}
}
我想以通用方式做同样的事情。如何重新创建上述方法的代码? 我尝试执行下面的代码,但它不起作用。 已编辑:方法名称已更改
public List<TPer> getDATA_Generic<TPer, TDal>(TPer per, int acao)
where TDal: new()
{
TDal _dal = new TDal();
List<TPer> _lst = new List<TPer>();
try
{
_lst = _dal.getDATA(TPer,acao); //**EDITED**: The call for getDATA method was changed
}
catch (Exception e)
{
throw e;
}
finally
{
_dal = default(TDal);
}
return _lst;
}
已编辑:上面的代码有效,但我不想这样做:
public List<TPer> getDATA<TPer, TDal>(TPer per, int acao)
已编辑:相反,我想要这样的东西:
public List<TPer> getDATA<TPer>(TPer per, int acao)
已编辑:并在方法内创建一个新的 TDal 实例,我不知道这是否可能,或者是否存在解决此问题的解决方法:
TDal _dal = new TDal();
其实我有几个课,类似这样的:
BussinesRuleA: method getDATA, call to persitenceRuleA , dalRuleA
BussinesRuleB: method getDATA, call to persitenceRuleB , dalRuleB
BussinesRuleC: method getDATA, call to persitenceRuleC , dalRuleC
我想减少代码的重写,避免写很多方法,我想用泛型的TPer和TDal来做这个:
BussinesRuleA: method getDATA<T>, call to TPer , TDal
BussinesRuleB: method getDATA<T>, call to TPer , TDal
BussinesRuleC: method getDATA<T>, call to TPer , TDal
【问题讨论】:
-
重构后的代码有什么问题?
-
与
persitenceRule有什么共同点吗?它们是否继承自同一个基类? -
您应该尝试将其发布到 stackexchange 的 codereview 子站点。
-
@nandox - 使用 @ + 用户名。当您回复他们时,它会提醒他们。
-
谢谢@gunr2171。不,它们不是从基类继承的。并且通用代码有效,但我不知道如何创建 TDal 的实例而不将 TDal 放在方法的声明中。
标签: c# generics optimization methods