在给定基类对象的情况下区分多个派生类对象

时间:2019-09-25 14:10:24

标签: c#

我最终有一个奇怪的要求。我有一个基类的多个派生类,如下所示。

class base
{
}

class derived1 : base
{
}
class derived2 : base
{
}
.
.
.
.
class derivedN : base
{
}

void someFunction(base bObj)
{
//get me derived class object with which bObj was created.
}

现在在我的代码中,我得到了基类对象(这是一个函数的参数)。此函数可以提取从中创建此基类对象的确切派生类对象吗?

这可能没有道理,但我强烈认为必须有办法。

3 个答案:

答案 0 :(得分:3)

C#是一种静态类型的语言。

这意味着,必须在编译时 知道对象的类型。

具有:

void someFunction(Base bObj)
{
    // bObj.Derived1Method() if bObj is Derived1
    // or
    // bObj.Derived2Method() if bObj is Derived2
}

您遇到了麻烦。

有两种方法。您可以使用模式匹配:

switch (bObj)
{
    case Derived1 d1:
        d1.Derived1Method();
        break;

    case Derived2 d2:
        d2.Derived2Method();
        break;
}

优点:静态类型,类型安全。
缺点:违反了SOLID的开放式原则。

或者您去dynamic并使用双重调度:

void someFunction(Base bObj)
{
    dynamic d = (dynamic)bObj;
    DoSomething(d);
}

void DoSomething(Derived1 d1) => d1.Derived1Method();

void DoSomething(Derived2 d2) => d2.Derived2Method();

优点:???
缺点:速度慢,输入不安全,会在运行时抛出。

答案 1 :(得分:2)

如果要检查实例的类型是否正确,则:

switch (bObj.GetType())
{
      case typeof(derived1):

          Console.WriteLine("bObj is an instance of derived1");
          break;
      case typeof(derived2):
          Console.WriteLine("bObj is an instance of derived2");
          break;
      .....................
      case typeof(derivedn):
          Console.WriteLine("bObj is an instance of derivedn");
          break;
      default:
          Console.WriteLine("bObj is instance of base");
          break;
}

答案 2 :(得分:0)

void someFunction(base bObj)
{
    if (bObj is derived1)
    {

    }
    else if(bObj is derived2)
    {

    }
    ...
}
相关问题