C#检查父类中子类的类型。这是好习惯吗?

时间:2018-08-01 11:13:28

标签: c# inheritance

想象一下我们有这两个类:

public class A 
{
   void DoA()
   {
      if(condition1)
      {
         AnotherClass.MethodA();
      }
   {
}

public class B 
{
   void DoB()
   {
      if(condition1)
      {
         AnotherClass.MethodB();
      }
   {
}

代码是相同的,只是它们在AnotherClass中调用不同的方法。因此,实现父类似乎是避免重复代码的好主意:

public class Parent
{
   void DoParent()
   {
      if(condition1)
      {
         if(GetType() == typeof(A)
         {
            AnotherClass.MethodA();
         }
         else if(GetType() == typeof(B))
         {
            AnotherClass.MethodB();
         }
      }
   {
}

但是在父级中检查子类的类型感觉不对。这是好习惯吗?如果没有,我有什么选择?

0 个答案:

没有答案
相关问题