重写(投) [英] Overriding (cast)

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

问题描述

如果我有一个基类和两个派生类,我想通过手工来实现两个派生类之间的铸造,有没有办法做到这一点? (在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列表值是'乐特。
还等什么,如果有三个或更多的实现类(如工资,每小时,顾问,和前任员工。)

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类,我不需要因为'雇员将只能是在任一时刻的选择之一的新对象。

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

推荐答案

您必须实现的明确隐含运算符

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天全站免登陆