gpt4 book ai didi

c# - 具有更严格约束的继承方法?

转载 作者:行者123 更新时间:2023-11-30 14:13:33 24 4
gpt4 key购买 nike

假设我有以下内容:

class EntityContainer : Container { }
class EntityComponent : Component { }

容器有两种向容器中添加新组件的方法,它们是:

Add(IComponent component)
Add(IComponent component, string name)

但是,假设我希望我的 EntityContainer 类采用 EntityComponent 对象,而不是任何实现 IComponent

起初,我以为我可以简单地隐藏或覆盖基类的 Add() 方法,但似乎签名必须完全匹配。那么,最好的方法是什么?

最佳答案

“重写”Add 方法使其接收更具体的类型不会满足您的接口(interface)暗示的契约。

你说Container接口(interface)有这些方法:

void Add(IComponent component);
void Add(IComponent component, string name);

但是你只想允许 EntityContainer 实例(它实现了 IComponent),所以基本上你想要这样:

void Add(EntityComponent component);
void Add(EntityComponent component, string name);

您不能像这样实现(甚至不能在语义上)Container 接口(interface),因为在您的接口(interface)中您说您可以添加任何实现 IComponent 的元素。您正在更改原始契约(Contract)!

正如 Morten 在评论中指出的那样,您可以这样做:

class EntityContainer : Container { 
void Add(IComponent component) {
var entityComponent = component as EntityComponent;
if(entityComponent == null)
throw new InvalidOperationException("Can only add EntityComponent instances");
// Actual add...
}
// Other methods..
}

但我建议您不要那样做。打破接口(interface)所暗示的契约应该是异常(exception),而不是规则。此外,如果您这样做,您将无法知道 Container 在运行时真正期望的是什么。这不是一种直观的行为,很可能会导致微妙的问题。如果只想接受特定类型的组件,可以使用泛型。通过这种方式,你不仅可以应用你想要的约束,你还可以获得强类型,你的意图会更明确。它看起来像这样:

interface Container<T> where T : IComponent {
void Add(T component);
void Add(T component, string name);
}

这意味着您的容器将容纳指定类型的元素,但它应该实现(或扩展,如果它是一个类)接口(interface) IComponent。所以你不能创建 Container<Object> ,因为它没有实现 IComponent。

您的 EntityContainer 看起来像这样:

class EntityContainer : Container<EntityComponent> { 
void Add(EntityComponent component) {
// Actual add...
}
// Other methods..
}

关于c# - 具有更严格约束的继承方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14008478/

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