C#声明了两者,类和接口

Ste*_*gas 7 c# encapsulation interface declaration

// interface
public interface IHasLegs { ... }

// base class
public class Animal { ... }

// derived classes of Animal
public class Donkey : Animal, IHasLegs { ... } // with legs
public class Lizard : Animal, IHasLegs { ... } // with legs
public class Snake : Animal { ... } // without legs

// other class with legs
public class Table : IHasLegs { ... }

public class CageWithAnimalsWithLegs {
    public List<??> animalsWithLegs { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我应该把什么?给力来自两个继承的对象AnimalIHasLegs?我不想Snake在那个笼子里看到一个Table.

--------------编辑--------------

谢谢大家的答案,但事情就是这样:我真正想做的是:

public interface IClonable { ... }
public class MyTextBox : TextBox, IClonable { ... }
public class MyComboBox : ComboBox, IClonable { ... }
Run Code Online (Sandbox Code Playgroud)

TextBox/ComboBox当然是一个控件.现在,如果我创建一个继承Control和IClonable的抽象类,我将松开我需要的TextBox/ComboBox继承.不允许多类继承,因此我必须使用接口.现在我再次想到它,我可以创建另一个继承自IClonable的接口:

public interface IClonableControl : IClonable { ... }
public class MyTextBox : TextBox, IClonableControl { ... }
public class MyComboBox : ComboBox, IClonableControl { ... }
Run Code Online (Sandbox Code Playgroud)

然后

List<IClonableControl> clonableControls;
Run Code Online (Sandbox Code Playgroud)

谢谢!!

Roy*_*tus 17

首先,Animals对于一个类名来说,这是一个糟糕的选择Animal.类名应该是单数.此类也应该声明abstract,因为它只是具体类型的基类,如Donkey.

其次,您可以定义一个名为LeggedAnimal继承自Animal和的抽象类IHasLegs.然后你可以继承DonkeyLeggedAnimal

最后,你可以说List<LeggedAnimal>,你很高兴去!


Mar*_*ell 10

没有直接的概念List<T where T : Animals, IHasLegs>.您可以向上移动T一个级别到笼子 - 但是然后调用者必须指定T满足两个约束的个体:

class Cage<T> where T : Animal, IHasLegs {
    public List<T> Items {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

它可以是Cage<Lizard>,例如 - 或(单独)Cage<Donkey>- 但你仍然不能用它来存储任何 Animal有腿的东西 - 即你不能使用这个概念将a Lizard和a Donkey放在同一个笼子里.


gsh*_*arp 3

你为什么不开设一个 AnimalwithLegs 类?

public abstract class AnimalWithLegs : Animal, IHasLegs{}
Run Code Online (Sandbox Code Playgroud)

然后

public class CageWithAnimalsWithLegs 
{
   public List<AnimalWithLegs>  AnimalWithLegs { get; set; }
}
Run Code Online (Sandbox Code Playgroud)