将 B 添加到 List<A<object>>,其中 B 以值类型实现 A
Add B to List<A<object>>, where B implements A with a value type
给定以下类型和片段:
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()
};
给定以下类型和片段:
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()
};