并行继承链中的多态性和类型安全性 [英] Polymorphism AND type safety in parallel inheritance chains

查看:158
本文介绍了并行继承链中的多态性和类型安全性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个并行继承链:

  Chain1:
动物< - Lion
< ; - Gazelle

Chain2:
Food < - Meat
< - Grass

我想在Animal上实现Eats多态属性。这是它的样子:

  public abstract class Animal 
{
public abstract Food Eats {get ; set;}
}


公共类Lion:Animal
{
public override Food Eats
{
get {return新的Meat();}
set
{
if(value is Meat)DoSomething(value);
另外抛出新的异常(狮子只吃肉。+
你最好学习这个,老兄!);
}
}
}

然而,这段代码并不是类型安全。我应该用草喂狮子吗,我只会在运行时遇到我的bug。



有人可以给我提供一个代码示例,它有助于在不牺牲多态性的情况下使用泛型进行类型安全吗?

解决动物可以是一个泛型类:

  public abstract class Animal< T> T:食物
{
public abstract T Eats {get; set;}
}

然后你可以让狮子成为这样的肉食动物

  public class Lion:Animal< Meat> 
{
//等等...
}

但是这不是一个最佳解决方案。你不能再使用动物作为多态接口,因为你需要知道使用它的细节。这可能不是多态的地方。


I have two parallel inheritance chains:

Chain1:
Animal <- Lion
       <- Gazelle

Chain2:
Food   <- Meat
       <- Grass

I want to implement the "Eats" polymorphic property on Animal. This is how it looks like:

public abstract class Animal
{
  public abstract Food Eats { get; set;}
}


public class Lion : Animal
{
  public override Food Eats
  {
     get { return new Meat();}
     set 
     {
       if (value is Meat) DoSomething(value);
       else throw new Exception("Lions only eat meat. " + 
                                "You better learn that, dude!");
     }
  }
}

However, this code is not type safe. Should I feed my Lion with grass, I will be confronted with my bug only in runtime.

Could someone provide me with a code example that facilitates type safety using Generics without sacrificing polymorphism?

解决方案

Animal can be a generic class:

public abstract class Animal<T> where T : Food
{
    public abstract T Eats {get;set;}
}

then you can make lion a meat eating animal like this

public class Lion : Animal<Meat>
{
    //etc...
}    

But this is not be an optimal solution. You can't use animal as a polymorphic interface any more because you need to know details about it's implementation to use it. This might just not be the place for polymorphism.

这篇关于并行继承链中的多态性和类型安全性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆