c# - 如何定义具有泛型类型的接口或类谁的泛型类型拥有泛型类型
问题描述
我想定义一个有多个(特殊和正常)房间的房子,每个房间都有一系列(特殊和正常)东西。
我开始为我的 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 指令或程序集引用?)
解决方案
您不能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
{ }
或者您可以使用已声明为通用约束的接口(更改TThing
为IThing
and ISpecialThing
:
// Room(s)
public interface Room<TThingCollection> where TThingCollection : ThingCollection<IThing> { }
public interface SpecialRoom<TThingCollection> : Room<TThingCollection> where TThingCollection : SpecialThingCollection<ISpecialThing> { }
推荐阅读
- django - Django Channels,即时实例化一个新的消费者,没有链接到 Websocket 或其他协议?
- excel - 使用 PowerShell 将范围从一个工作簿表复制到另一个工作簿表
- sql - 根据我在 SQL Server 2016 中给出的时区格式化日期
- python - PyInstaller:ValueError:模块文件...丢失
- android - System.err:调用 js 方法 onCreate 失败 - 缺少主条目。应用程序无法启动。验证应用引导程序
- shopify - Shopify 页面模板部分与另一个页面的不同数据
- artifactory - 为什么我无法获取托管在云上的工件存储库中的工件,即使在使用 davfs 成功挂载它之后也是如此
- javascript - 我可以从 this.props.style 中添加或减去像素吗?
- path - GhostScript.net 无法识别文件名中的特殊字符
- javascript - 动态表每一行的定时器