C# 覆盖(强制转换)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/725435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 22:39:05  来源:igfitidea点击:

Overriding (cast)

c#casting

提问by DevinB

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#)

如果我有一个基类和两个派生类,我想手动实现两个派生类之间的转换,有什么办法可以做到吗?(在 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;
}

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

通常,我将从 Imp_A -> Imp_B 进行转换,并且我希望 E 列表中的最后一个值是“LastE”。另外,如果有三个或更多的实现类(例如 Salary、Hourly、Consultant 和前任雇员)会怎样。

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

不管这在架构上是否合理(我无法描述整个应用程序并且简明扼要)有可能吗?

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.

我打算编写一个转换器,但据我所知,转换器将创建 Imp_B 类的新对象,我不需要它,因为“员工”在任何时候都只是选项之一。

-Devin

-德文

采纳答案by Daniel Brückner

You must implement a explicitor implicitoperator.

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

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;

回答by mqp

I'd suggest you write Imp_B like this, if possible:

如果可能的话,我建议你这样写 Imp_B:

class Imp_B : Imp_A
{
    private int A;
    private int B;
    private int C;
    private int D;
    private int lastE { get { return this.E.Last(); } }
}

If you can't actually derive from ImpB, it's impossible for you to "treat" a ImpA object as an ImpB transparently the way you'd like, because they just aren't the same thing in memory. So, implement an explicit conversion.

如果您实际上不能从 ImpB 派生,那么您就不可能按照您希望的方式透明地将 ImpA 对象“处理”为 ImpB,因为它们在内存中并不是一回事。因此,实现显式转换。