gpt4 book ai didi

c# - 在定义上强制使用确切的类

转载 作者:太空宇宙 更新时间:2023-11-03 13:16:20 25 4
gpt4 key购买 nike

假设我有几个类:

public class ParentClass
{
<common functionality>
...
}

public class ChildClass : ParentClass
{
<additional functionality>
...
}

在我的代码中,我同时使用了 ParentClassChildClass 类型的对象 - 有时我不需要 ChildClass 和有时我会。 (实际上还涉及几代的类,但让我们保持简单。)有没有办法做到这一点,如果我这样声明一个对象:

public ParentClass thing;

不会稍后将 thing 定义为:

thing = new ChildClass();

我希望多态性达到 ChildClass 继承所有 ParentClass 功能的程度,但我不希望在定义时能够使用更具体的类一个东西。我可以以某种方式禁止这样做吗?当然,我可以将 ParentClass 抽象化,但这样我就无法拥有 ParentClass 类型的对象,而我有时确实需要它们。

最佳答案

确保这一点的唯一方法是将定义的工厂传递给您的代码,然后代码将创建 ParentClass 并且不允许其他子类。

public ParentClass thing;
thing = ParentClassFactory.Build();

问题是将工厂推送到您的代码,但它可以让您控制此时设置的实例类型。

关于c# - 在定义上强制使用确切的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25977838/

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