gpt4 book ai didi

c# - 是否可以在不强制转换的情况下在 C# 中实现 "virtual constructor"模式?

转载 作者:可可西里 更新时间:2023-11-01 09:10:53 25 4
gpt4 key购买 nike

我正在编写一个由 C# 编写的程序,该程序最终会被编译成一个应用程序。我希望每个生成的类型都提供一个“深度克隆”功能来复制整个数据树。也就是说,我希望有人能够做到:

var x = new Base(); // Base has public virtual Base DeepClone() { ... }
var y = new Derived(); // Derived overrides DeepClone
Base a = x.DeepClone();
Base b = y.DeepClone();
// Derived c = x.DeepClone(); // Should not compile
Derived d = y.DeepClone(); // Does not compile, DeepClone returns Base

代替

var x = new Base();
var y = new Derived();
Base a = x.DeepClone();
Base b = y.DeepClone();
// Derived c = x.DeepClone(); // Should not compile
Derived d = (Derived)y.DeepClone();

但是,C# 不允许您在简单的覆盖中执行此操作;覆盖必须返回与基上声明的类型相同的类型。

既然我编写的代码无论如何都会消除样板,那么我可以生成一些东西来允许第一个 block 编译吗?我尝试了类似于以下内容的操作:

abstract class Base
{
public abstract Base DeepClone();
}

class Base2 : Base
{
int Member { get; set; }

public Base2() { /* empty on purpose */ }
public Base2(Base2 other)
{
this.Member = other.Member;
}

public override Base2 DeepClone()
{
return new Base2(this);
}
}

sealed class Derived : Base2
{
string Member2 { get; set; }

public Derived() { /* empty on purpose */ }
public Derived(Derived other)
: base(other)
{
this.Member2 = other.Member2;
}

public override Derived DeepClone()
{
return new Derived(this);
}
}

但这不会编译,因为覆盖不匹配。我还尝试从基础覆盖该方法并使用“new”关键字将其隐藏,但这也不起作用。

最佳答案

是的,它是可行的,但是您必须将抽象方法从公共(public)方法转移到 protected 方法,然后创建一个只调用 protected 方法的公共(public)非抽象函数。派生类只需要实现 protected 函数并可以隐藏公共(public)函数,执行本应由客户端执行的转换。

abstract class Base
{
public Base DeepClone()
{
return CloneInternal();
}

protected abstract Base CloneInternal();
}

class Base2 : Base
{
int Member { get; set; }

public Base2() { /* empty on purpose */ }
public Base2(Base2 other)
{
this.Member = other.Member;
}

new public Base2 DeepClone()
{
return (Base2)CloneInternal();
}

protected override Base CloneInternal()
{
return new Base2(this);
}
}

sealed class Derived : Base2
{
string Member2 { get; set; }

public Derived() { /* empty on purpose */ }
public Derived(Derived other)
: base(other)
{
this.Member2 = other.Member2;
}

new public Derived DeepClone()
{
return (Derived)CloneInternal();
}

protected override Base CloneInternal()
{
return new Derived(this);
}
}

关于c# - 是否可以在不强制转换的情况下在 C# 中实现 "virtual constructor"模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30083354/

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