不继承泛型接口的非泛型类实现

本文关键字:泛型类 实现 继承 泛型接口 | 更新日期: 2023-09-27 18:33:15

如果我有这个代码:

public interface IThing<T> where T : class
{
    // ...
}
public class BaseThing<T> : IThing<T> where T : class
{
    // ...
}
public class ThingA : BaseThing<string>
{
    // ...
}
public class ThingB : BaseThing<Uri>
{
    // ...
}

此代码失败:

List<IThing<object>> thingList = new List<IThing<object>>();
thingList.Add(new ThingA());
thingList.Add(new ThingB());

即使ThingA(间接)继承自(并且应该是)IThing<T> .为什么?ThingA/ThingB不是IThing<T>的实例吗?

不继承泛型接口的非泛型类实现

这将要求你的接口是协变的。 有关详细信息,请参阅泛型中的协方差和逆变。

在这种情况下,您可以使用以下方法完成这项工作:

// Add out here
public interface IThing<out T> where T : class
{
}

请注意,这确实对接口以及您可以使用它执行的操作施加了限制,因为它要求接口中的类型T仅用作接口内的方法返回类型,而不用作形式方法参数的类型。

如果这不可行,另一种选择是创建一个非泛型IThing接口,并让IThing<T>实现IThing。 然后,您可以将List<IThing>用于您的收藏。