如何在c#中优化冗余代码?

时间:2014-07-14 14:48:32

标签: c# generics optimization methods

我有以下课程。编辑:(我知道这不是一个好习惯):

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

1 个答案:

答案 0 :(得分:1)

不可能对特定构造函数的可用性设置泛型约束,因此您无法在方法内部保证TDal _dal = new TDal(_connectionString);是可能的。

我会重构它然后在外部提供dal:

public List<TRule> getData<TRule>(TRule perRA, IDal<TRule> dalRA, int acao)
{
    List<TRule> list = new List<TRule>();
    try
    {
        list = dalRA.getDATA(perRA, acao);
    }
    catch (Exception e)
    {
        throw e;
    }
    finally
    {
        dalRA = null;
    }
    return list;
}

假设:

internal interface IDal<TRule>
{
    List<TRule> getDATA(TRule perRA, int acao);
}