【问题标题】:How define a interface or class with a generic type who's generic type holds a generic type如何用泛型类型定义接口或类,泛型类型持有泛型类型
【发布时间】:2019-07-21 00:23:52
【问题描述】:

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

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

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

代码:

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 指令或程序集引用?)

【问题讨论】:

  • 请避免添加代码或错误消息的屏幕截图 - 它们通常只会使问题更难阅读。相反,将它们作为文本包含在内。由于您已经提供了正确的代码,因此我已从您的帖子中删除了图像。欲了解更多信息,请阅读"Why not upload images of code on SO when asking a question?" 接受的答案。

标签: c# oop generics types interface


【解决方案1】:

你不能在泛型约束中使用TThing作为类型参数,除非它也在方法的签名中定义——所以Room&lt;TThingCollection&gt;应该变成Room&lt;TThingCollection, TThing&gt;—— 但要使其正常工作,您需要添加更多约束:

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

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

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

【讨论】:

    【解决方案2】:

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

    如果没有这些集合更改,它将无法工作。

    感谢您的帮助,非常感谢!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-22
      • 2016-10-16
      • 2015-01-18
      • 1970-01-01
      • 2019-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多