抽象类设计

use*_*348 4 c# oop abstract-class

这是一个可接受的设计吗?

抽象类

public abstract class SomethingBase
{ 
   public abstract int Method1(int number1);
   public abstract int Method2(int number2); 
} 

public class Class1 : SomethingBase
{
   public override int Method1(int number1)
   {
      //implementation
   }

   //i dont want this method in this class
   public override int Method2(int number2)
   {
        throw new NotImplementedException();
   }
}

public class Class2 : SomethingBase
{

   //i dont want this method in this class
   public override int Method1(int number1)
   {
     throw new NotImplementedException();
   }

   public override int Method2(int number2)
   {
    //implementation
    }
}
Run Code Online (Sandbox Code Playgroud)

我的意思是如果我需要在我的Class1中使用method1而不需要方法2而在类2中需要vica verse.实际上,这些方法在派生类中相互排斥.

Wim*_*dse 9

它不是一个可接受的设计.为了使其更可接受,您可以在抽象类上实现两个接口.一个for Method1()和一个for Method2(),只需使用接口对象传递它.

您真的不想使用Class1Class2定义,因为您的客户端存在调用未实现的方法的危险.所以我建议使用接口并使用它们.