1

I have an interface:

interface IFoo<out T> 
{
   T Get();
}

and some instances like IFoo<int> a, IFoo<User> u, IFoo<string> s and etc. There is a List<IFoo<object>> used to collect them. But variance doesn't work for value types, is there a proper way to put them in the list?


It doesn't look like you need generics for this list, so you can have the interface implement a non-generic interface:

interface IFoo<out T> : IFoo { }

That way, all of your objects implement the same interface. This may not be a bad idea, since they do have something in common. Now you can simply use a List<IFoo>.

4

1 回答 1

3

看起来您不需要此列表的泛型,因此您可以让接口实现非泛型接口:

interface IFoo<out T> : IFoo { }

这样,您的所有对象都实现了相同的接口。这可能不是一个坏主意,因为它们确实有一些共同点。现在您可以简单地使用List<IFoo>.

于 2011-10-10T05:38:46.553 回答