Spl*_*Xor 3 c# generics interface
我有一个名为的接口Man.在这个接口中,我有一个getList()返回类型T列表的方法(依赖于实现接口的类).我有3类实现Man:small,normal,和big.每个类都有方法getList()thart返回列表small或列表normal或列表big.
interface Man<T>{
List<T>getList();
}
class small : Man<small>{
List<small> getList(){
return new List<small>();
}
}
class normal : Man<normal>{
List<normal> getList(){
return new List<normal>();
}
}
class big : Man<big>{
List<big> getList(){
return new List<big>();
}
}
Run Code Online (Sandbox Code Playgroud)
现在我有了类:Home 它包含一个参数bed,它是一个实例Man.
Bed可以是各种类型的:small,normal,big.如何声明类型参数bed?
class Home{
Man bed<> // what i must insert between '<' and '>'??
}
Run Code Online (Sandbox Code Playgroud)
你需要制作Home通用的:
class Home<T>
{
Man<T> bed;
Run Code Online (Sandbox Code Playgroud)
编辑以回应评论:
如果您不知道将存在什么类型的"Man",另一种选择是使您的泛型类实现非泛型接口:
public interface IBed { // bed related things here
public class Man<T> : IBed
{
// Man + Bed related stuff...
class Home
{
IBed bed; // Use the interface
Run Code Online (Sandbox Code Playgroud)
然后,您可以根据接口定义的共享协定进行开发,并允许IBed在其中使用任何类型的协议Home.
在一个不相关的附注中,我建议在这里使用更好的命名方案 - 名称没有多大意义......为什么一个名为"床"的"男人"?您可能还想查看标准的大写约定.