从抽象类调用的泛型助手类

本文关键字:泛型 抽象类 调用 | 更新日期: 2023-09-27 18:13:49

我有一些通用的助手方法。我希望能够从一个抽象类内调用一个,但我没有派生类型传递到泛型方法。我怎么得到它?我不想让抽象类也是泛型的。这可能吗?!这里是一些不工作的代码…:"(

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

和helper类代码

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;
        }
    }
}

从抽象类调用的泛型助手类

只是一个建议,您还可以将helper定义为扩展方法,将泛型类型参数移动到该方法,将类型参数限制为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

抽象基类不能"知道"任何派生类的类型。

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

protected abstract void Save(…);

然后调用这个抽象方法,而不是直接调用helper方法。派生类可以重写它,它们将知道它们自己的类型:

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