覆盖(强制转换) [英] Overriding (cast)

查看:153
本文介绍了覆盖(强制转换)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I have a base class and two derived classes, and I want to implement the casting between the two derived classes by hand, is there any way to do that? (in 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;
}

一般来说,我将从Imp_A - > Imp_B投放,值在E列表中为LastE。
另外,如果有三个或更多的实现类(如Salary,Hourly,Consultant和前雇员)。

Generally I'll be casting from Imp_A -> Imp_B and I want the last value in the E list to be the 'LastE'. Also, what if there were three or more implementation classes (such as Salary, Hourly, Consultant, and Former Employees.)

无论是在架构上声音(我不能描述整个应用程序和简洁)是可能的吗?

Regardless of whether this is architecturally sound (I can't describe the whole application and be concise) is it possible?

我要写一个转换器,除了我的理解一个转换器将创建Imp_B类的一个新对象,我不需要,因为employee只能是任何一个时间的选项之一。

I was going to write a converter, except that to my understanding a converter will create a new object of the Imp_B class, which I don't need because the 'employee' will only be one of the options at any one time.

-Devin


-Devin

推荐答案

您必须实施 explicit implicit 运算符。

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

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

Now you can do the following.

Imp_A a = new Imp_A();
Imp_B b = (Imp_B) a;

这篇关于覆盖(强制转换)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆