2

如果我有这个代码:

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>

4

1 回答 1

7

This would require your interface to be covariant. For details, see Covariance and Contravariance in Generics.

In this case, you can make this work by using:

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

Note that this does place limitations on the interface and what you can do with it, however, as it requires that the type T in the interface be used only as a method return type within the interface, and not used as a type of formal method parameters.

If this is not viable, another option is to create a non-generic IThing interface, and have IThing<T> implement IThing. You could then use List<IThing> for your collection.

于 2013-09-27T18:21:44.973 回答