gpt4 book ai didi

c# - 超越(转换)

转载 作者:可可西里 更新时间:2023-11-01 08:34:59 27 4
gpt4 key购买 nike

如果我有一个基类和两个派生类,我想手工实现两个派生类之间的转换,有什么办法吗? (在 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 和 Former Employees)怎么办。

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

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

-德文

最佳答案

您必须实现 explicitimplicit运营商。

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

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

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

关于c# - 超越(转换),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/725435/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com