给定以下类型和片段:
interface IFoo<out T> {
T doThing();
}
class Bar : IFoo<int> {
int doThing() => 0;
}
var list = new List<IFoo<object>> {
new Bar() //fails to compile
};
据我了解,无法添加 Bar
到 List<IFoo<object>>
,因为Bar
的T
是一个值类型。
鉴于我需要IFoo
类型安全,我该如何更改 Bar
或集合,以便可以存储 IFoo<T>
对于某些值和引用类型?
最佳答案
基本上我在这里只看到一个选项:
public interface IFoo<out T>:IFoo
{
T doThing();
}
public interface IFoo
{
object doThing();
}
public class Bar : IFoo<int>
{
public int doThing(){return 0;}
object IFoo.doThing()
{
return doThing();
}
}
var list = new List<IFoo>
{
new Bar()
};
关于c# - 将 B 添加到 List<A<object>>,其中 B 使用值类型实现 A,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36229893/