加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 01:52:06 所属栏目:百科 来源:网络整理
导读:假设我有以下内容: class EntityContainer : Container { }class EntityComponent : Component { } Container有两种向容器添加新组件的方法,它们是: Add(IComponent component)Add(IComponent component,string name) 但是,假设我希望我的EntityContainer
假设我有以下内容:

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

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

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

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

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

解决方法

‘覆盖’Add方法,以便它接收更具体的类型将无法满足您的接口所暗示的合同.

你说Container接口有这些方法:

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

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

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

你不能像这样实现(甚至不是语义上)Container接口,因为在你的接口中你说你可以添加任何实现IComponent的元素.你正在改变原来的合同!

正如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..
}

但我建议你不要这样做.打破界面所暗示的合同应该是例外,而不是规则.此外,如果您这样做,在运行时之前您无法知道Container真正期望的内容.这不是一种直观的行为,它很可能会导致细微的问题.如果您只想接受特定类型的组件,则可以使用泛型.通过这种方式,您不仅可以应用您想要的约束,还可以获得强力打字,并且您的意图将更加清晰.它看起来像这样:

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

这意味着您的容器将保存指定类型的元素,但它应该实现(或扩展,如果它是一个类)接口IComponent.因此,您无法创建Container< Object>,因为它不实现IComponent.

您的EntityContainer将如下所示:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读