Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用泛型类型定义接口或类谁的泛型类型持有泛型类型_C#_Oop_Generics_Types_Interface - Fatal编程技术网

C# 如何使用泛型类型定义接口或类谁的泛型类型持有泛型类型

C# 如何使用泛型类型定义接口或类谁的泛型类型持有泛型类型,c#,oop,generics,types,interface,C#,Oop,Generics,Types,Interface,我想定义一个有多个特殊和普通房间的房子,每个房间都有一系列特殊和普通的东西 我开始在ThingCollectionand派生类中使用泛型,但当我想定义房间类型时,我的泛型类型定义开始出现错误 有人知道定义接口/类的正确方法吗,这样我就不会收到这个错误消息了 代码: 错误消息: CS0246:找不到类型或命名空间名称“TThing”是否缺少using指令或程序集引用 除非在方法的签名中也定义了TThing,否则不能在泛型约束中使用TThing作为类型参数-因此Room应该变成Room- 但要使其起

我想定义一个有多个特殊和普通房间的房子,每个房间都有一系列特殊和普通的东西

我开始在ThingCollectionand派生类中使用泛型,但当我想定义房间类型时,我的泛型类型定义开始出现错误

有人知道定义接口/类的正确方法吗,这样我就不会收到这个错误消息了

代码:

错误消息:

CS0246:找不到类型或命名空间名称“TThing”是否缺少using指令或程序集引用

除非在方法的签名中也定义了TThing,否则不能在泛型约束中使用TThing作为类型参数-因此Room应该变成Room- 但要使其起作用,您需要添加更多约束:

public interface Room<TThingCollection<TThing>> 
    where TThingCollection : ThingCollection<TThing> 
    where TThing : IThing
{ }

public interface SpecialRoom<TThingCollection<TThing>> : Room<TThingCollection> 
    where TThingCollection : SpecialThingCollection<TThing> 
    where TThing : ISpecialThing
{ }

@Zohar你给出的答案让我对代码进行了一些重构

我使用了您代码的这一部分:

// Room(s)
public interface Room<TThingCollection> where TThingCollection : ThingCollection<IThing> { }
public interface SpecialRoom<TThingCollection> : Room<TThingCollection> where TThingCollection : SpecialThingCollection<ISpecialThing> { }
我还必须将集合接口更改为:

// Collection(s)
public interface ThingCollection<TThing> where TThing : IThing { }
public interface SpecialThingCollection<TSpecialThing> : ThingCollection<IThing> where  TSpecialThing : ISpecialThing{ }
如果没有这些集合更改,它将无法工作


谢谢你的帮助,非常感谢

请避免添加代码截图或错误消息-它们通常只会使问题更难阅读。而是将它们作为文本包含。由于您已经提供了正确的代码,我已经从您的帖子中删除了这些图像。有关更多信息,请阅读的公认答案。
// Room(s)
public interface Room<TThingCollection> where TThingCollection : ThingCollection<IThing> { }
public interface SpecialRoom<TThingCollection> : Room<TThingCollection> where TThingCollection : SpecialThingCollection<ISpecialThing> { }
// Collection(s)
public interface ThingCollection<TThing> where TThing : IThing { }
public interface SpecialThingCollection<TSpecialThing> : ThingCollection<IThing> where  TSpecialThing : ISpecialThing{ }