代码之家  ›  专栏  ›  技术社区  ›  René Vogt

一般约束忽略协方差

  •  7
  • René Vogt  · 技术社区  · 8 年前

    public interface IEnumerable<out T>
    { /*...*/ }
    

    那就是 co变体 在里面 T .

    然后我们有另一个接口和一个实现它的类:

    public interface ISomeInterface {}
    public class SomeClass : ISomeInterface
    {}
    

    现在协方差允许我们做以下事情

    IEnumerable<ISomeInterface> e = Enumerable.Empty<SomeClass>();
    

    所以 IEnumerable<SomeClass> 是可转让的 IEnumerable<ISomeInterface> .

    public void GenericMethod<T>(IEnumerable<T> p) where T : ISomeInterface
    {
        IEnumerable<ISomeInterface> e = p;
        // or
        TestMethod(p);
    }
    public void TestMethod(IEnumerable<ISomeInterface> x) {}
    

    我们得到了 告诉我们 IEnumerable<T> 无法转换为 IEnumerable<ISomeInterface>

    约束清楚地说明了 T 派生自 ISomeInterface IEnumerable<T> 是共同变体 T ,此任务应该有效(如上所示)。

    有什么技术原因不能在通用方法中工作吗?或者我错过了任何让编译器无法理解的东西?

    1 回复  |  直到 8 年前
        1
  •  7
  •   Backs    8 年前

    更改您的 GenericMethod 并添加通用约束 class :

    public void GenericMethod<T>(IEnumerable<T> p) where T : class, ISomeInterface
    {
        IEnumerable<ISomeInterface> e = p;
        // or
        TestMethod(p);
    }
    

    Covariance does not support structs ,所以我们需要告诉大家,我们只想使用类。