从抽象类调用的通用助手类

时间:2015-09-22 08:37:34

标签: c# .net generics abstract-class

我有一些通用的辅助方法。我希望能够从一个抽象类中调用一个,但我没有派生类型传递给Generic方法。我怎么得到它?我也不想让抽象类成为泛型。这可能吗?!这里有一些不起作用的代码......:'(

public abstract class Base
{
    public bool Save()
    {
        try
        {
            Helper<this.GetType()>.Save(this);
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }
}

辅助类代码

public class Helper<T> where T: class
{
    public static bool Save(T obj)
    {
        try
        {
            Context.DDBContext.Save<T>(obj);
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }
}

如果您想要更多代码,请询问。

2 个答案:

答案 0 :(得分:2)

只是一个建议,您也可以将助手定义为扩展方法,将泛型类型参数移动到方法,将类型参数限制为Base,然后您可以从派生类型调用它,就像它源于基地:

public static class Helper
{
    public static bool Save<T>(this T obj) where T: Base
    {
        try
        {
            Context.DBContext.Save<T>(obj);
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }               
}

public class Derived : Base{}

var x = new Derived();
x.Save();

然后您可以完全删除Base.Save

答案 1 :(得分:1)

你的抽象基类不能知道&#34;任何派生类的类型。

将对helper方法的调用委托给派生类,例如:通过在基类中定义抽象虚方法:

protected abstract void Save(…);

然后,不是直接调用helper方法,而是调用此抽象方法。派生类可以覆盖它,他们将知道他们自己的类型:

sealed class Derived : Base
{
    protected override void Save(…)
    {
        Helper<Derived>.Save(this);
    }
}