qJa*_*ake 2 c# generics inheritance
如果我有这个代码:
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>
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
此代码失败:
List<IThing<object>> thingList = new List<IThing<object>>();
thingList.Add(new ThingA());
thingList.Add(new ThingB());
Run Code Online (Sandbox Code Playgroud)
即使ThingA
(间接)继承自(并且应该是其实例)IThing<T>
.为什么?是ThingA
/ ThingB
不是IThing<T>
?
这将要求您的界面是协变的.有关详细信息,请参阅泛型中的协方差和逆变.
在这种情况下,您可以使用以下方法完成此工作:
// Add out here
public interface IThing<out T> where T : class
{
}
Run Code Online (Sandbox Code Playgroud)
请注意,这确实会对接口以及您可以对其执行的操作施加限制,因为它要求T
接口中的类型仅用作接口中的方法返回类型,而不是用作正式方法参数的类型.
如果这不可行,另一种选择是创建非通用IThing
接口,并IThing<T>
实现IThing
.然后List<IThing>
,您可以使用您的收藏.