c# - 将 B 添加到 List<A<object>>,其中 B 使用值类型实现 A

标签 c# generics inheritance covariance

给定以下类型和片段:

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

class Bar : IFoo<int> {
    int doThing() => 0;
}

var list = new List<IFoo<object>> {
    new Bar() //fails to compile
};

据我了解,无法添加 BarList<IFoo<object>> ,因为BarT是一个值类型。

鉴于我需要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/

相关文章:

c# - 使用 C# 从 Powershell 中解密 SecureString

Java 泛型 : Returning object of generic class with type parameter that is a super of argument T

java - 获取 "real"泛型类

java - 接口(interface)和继承编译时错误

c++ - 有没有办法在继承构造函数时访问初始化列表?

c# - setter 可以获取它所在的属性的名称吗

c# - MiniProfiler所需的Mini-Profiler-Resource文件夹从哪里获取?

c# - 选择列表逻辑应该位于 ASP.NET MVC、 View 、模型或 Controller 中的什么位置?

generics - 通用函数接受 &str 或移动字符串而不复制

c# - 抽象类和接口(interface)中可以使用相同的字段名称吗?