繁体   English   中英

区分多个派生 class 对象,具有给定的基本 class object

[英]differentiate between multiple derived class objects, with given base class object

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

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.
}

现在在我的代码的某个时刻,我得到了基础 class object (这是函数的参数)。 Can this function extract exact derived class object from which this base class object was created?

这可能没有意义,但我有一种强烈的感觉,一定有办法。

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的Open-Closed原则。

或者你 go dynamic并使用双重调度:

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

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

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

优点: ???
缺点:速度慢,类型不安全,可以在运行时抛出。

如果你想检查一个实例是否是一个确切的类型,那么:

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;
}
void someFunction(base bObj)
{
    if (bObj is derived1)
    {

    }
    else if(bObj is derived2)
    {

    }
    ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM