处理由于泛型继承而导致的方法定义重叠的最佳方法



我过去遇到过一个问题,我希望在一个抽象类中有两个方法,一旦实现,最终会有相同的方法定义。显然,我可以稍微不同地命名这些方法,但这似乎不雅,因为它们的目的相同。有没有比重命名更好的方法来处理这个问题?

public class foo
{
public string spam { get; set;}
}
public abstract class absService<T> where T : foo
{
protected void Validate(foo obj)
{
if (obj == null) throw new Exception("null obj");
}
protected abstract void Validate(T obj);
public object DoTheThing(T obj)
{
Validate((foo)obj);
Validate(obj);
//do stuff here
}
}
public class fooService : absService<foo>
{
protected override void Validate(foo Obj)
{
if (Obj.spam == null) throw new Exception("No spam");
}
}

您可以为此使用虚拟方法。

调用虚拟方法时,将检查对象的运行时类型是否有重写成员。派生程度最高的类中的重写成员被称为,如果没有派生类重写该成员,则该成员可能是原始成员。

好的部分是,您可以通过调用base来决定基类中的代码是否仍应运行。如果愿意,请验证((。如果不覆盖它(例如在另一个不进行更多验证的服务中(,则基本版本将运行。

public class foo
{
public string spam { get; set;}
}
public abstract class absService<T> where T : foo
{
// Default implementation
protected virtual void Validate(T obj) {
if (obj == null) throw new Exception("null obj");
}
public object DoTheThing(T obj)
{
Validate(obj); // Will call fooService.Validate() if overridden
//do stuff here
}
}
public class fooService : absService<foo>
{
protected override void Validate(foo Obj)
{
base.Validate(Obj); // Optional, to "extend" the base method.
if (Obj.spam == null) throw new Exception("No spam");
}
}

最新更新