【问题标题】:Add B to List<A<object>>, where B implements A with a value type将 B 添加到 List<A<object>>,其中 B 使用值类型实现 A
【发布时间】:2016-03-25 23:48:33
【问题描述】:

给定以下类型和sn-p:

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&lt;IFoo&lt;object&gt;&gt;,因为BarT 是一个值类型。

鉴于我需要 IFoo 类型安全,我该如何更改 Bar 或集合,以便可以同时存储 IFoo&lt;T&gt; 的某些值和引用类型?

【问题讨论】:

  • 你打算如何使用这个集合?
  • @GuruStron 仅用于访问doThing。显然,从中提取具有特定类型参数的项目是不安全的。 IFoo 上的类型安全是为直接操作它们的地方保留的,一旦它存储在集合中,我就可以失去这种安全。

标签: c# generics inheritance covariance


【解决方案1】:

基本上我在这里只看到一个选项:

    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()
    };

【讨论】:

  • 似乎合法,这正是两个标准IEnumerable 接口(通用和非通用)的工作方式。我会暂时接受接受,以免阻止替代解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-24
  • 2019-10-23
  • 2011-12-03
  • 2019-12-09
  • 2020-03-03
  • 2018-06-29
  • 1970-01-01
相关资源
最近更新 更多