【问题标题】:Best way to handle overlapping method definitions due to generic inheritance由于泛型继承,处理重叠方法定义的最佳方法
【发布时间】:2021-05-17 19:18:17
【问题描述】:

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

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

【问题讨论】:

    标签: c# .net generics abstract


    【解决方案1】:

    您可以为此使用virtual methods。

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

    不错的是,您可以根据需要调用 base.Validate() 来决定基类中的代码是否仍应运行。如果您不覆盖它 - 例如在另一个不进行更多验证的服务中 - 将运行基本版本。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-23
      • 1970-01-01
      相关资源
      最近更新 更多