覆盖(演员)

Dev*_*inB 11 c# casting

如果我有一个基类和两个派生类,并且我想手动实现两个派生类之间的转换,有没有办法做到这一点?(在C#中)

abstract class AbsBase
{
   private int A;
   private int B;
   private int C;
   private int D;
}

class Imp_A : AbsBase
{
   private List<int> E;
}


class Imp_B : AbsBase
{
   private int lastE;
}
Run Code Online (Sandbox Code Playgroud)

通常我会从Imp_A - > Imp_B进行转换,我希望E列表中的最后一个值是'LastE'.此外,如果有三个或更多实现类(例如Salary,Hourly,Consultant和Former Employees),该怎么办?

无论这在架构上是否合理(我无法描述整个应用程序并且简洁)是否可能?

我打算写一个转换器,除了据我所知,转换器将创建一个Imp_B类的新对象,我不需要它,因为'employee'在任何时候都只是其中一个选项.

-Devin

Dan*_*ner 25

您必须实现显式隐式运算符.

class Imp_A : AbsBase
{
   public static explicit operator Imp_B(Imp_A a)
   {
      Imp_B b = new Imp_B();

      // Do things with b

      return b;
   }
}
Run Code Online (Sandbox Code Playgroud)

现在您可以执行以下操作.

Imp_A a = new Imp_A();
Imp_B b = (Imp_B) a;
Run Code Online (Sandbox Code Playgroud)