首页 > 解决方案 > 如何定义具有泛型类型的接口或类谁的泛型类型拥有泛型类型

问题描述

我想定义一个有多个(特殊和正常)房间的房子,每个房间都有一系列(特殊和正常)东西。

我开始为我的 ThingCollection(和派生类)使用泛型,但是当我想定义我的 Room 类型时,我的泛型类型定义开始出现错误。

有谁知道定义我的接口/类的正确方法,所以我不会收到此错误消息?

代码:

namespace City.Street.House
{
    // Thing(s)
    public interface IThing{ }
    public interface ISpecialThing : IThing { }

    // Collection(s)
    public interface ThingCollection<TThing> where TThing : IThing { }
    public interface SpecialThingCollection<TThing> : ThingCollection<TThing> where TThing : ISpecialThing { }

    // Room(s)  // Error On TThing in both rows below:
    public interface Room<TThingCollection> where TThingCollection : ThingCollection<TThing> { } 
    public interface SpecialRoom<TThingCollection> : Room<TThingCollection> where TThingCollection : SpecialThingCollection<TThing> { }

    // House(s)
    public interface House { }
}

错误信息:

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

标签: c#oopgenericstypesinterface

解决方案


您不能TThing在泛型约束中用作类型参数,除非它也在方法的签名中定义 - 所以Room<TThingCollection>应该成为Room<TThingCollection, TThing>- 但要使其工作,您需要添加更多约束:

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
{ }

或者您可以使用已声明为通用约束的接口(更改TThingIThingand ISpecialThing

 // Room(s)
public interface Room<TThingCollection> where TThingCollection : ThingCollection<IThing> { }
public interface SpecialRoom<TThingCollection> : Room<TThingCollection> where TThingCollection : SpecialThingCollection<ISpecialThing> { }

推荐阅读