c# - 通用 with where 子句需要显式转换

标签 c# .net generics c#-4.0 type-constraints

我希望有人可以建议一种方法来避免对下面的“var o3”语句进行显式转换。看来编译器应该有足够的信息来隐式转换。

  using System.Collections.Generic;

  namespace Sample {

    public interface IPoint {
      double X { get; }
      double Y { get; }
    }

    public class Line<T> :List<T> where T:IPoint {}

    public class Graph<T> where T :IPoint {
      public Line<IPoint> Line1;
      public Line<T> Line2;

      public Graph() {
        var o1 = new Other(Line1); //works
        var o2 = new Other(Line2 as IEnumerable<IPoint>); //works
        var o3 = new Other(Line2); //error: cannot convert from 'Sample.Line<T>' to 'IEnumerable<Sample.IPoint>'
      }
    }

    public class Other {
      public Other(IEnumerable<IPoint> list) {}
    }

  }

最佳答案

您需要添加 classT 的约束Graph<T> 的类型参数类:

public class Graph<T> where T : class, IPoint

这是因为协方差不适用于结构:

new List<Int32>() is IEnumerable<IConvertible> == false
new List<String>() is IEnumerable<IConvertible> == true

虽然两者都是Int32String实现 IConvertible .

参见 Why covariance and contravariance do not support value type .

关于c# - 通用 with where 子句需要显式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21904508/

相关文章:

c# - .NET 运行时版本问题(supportedRuntime)

c# - 依赖注入(inject)到 {get;设置;} 属性

.net - 现有连接被远程主机强行关闭

c# - 如何在linq中查询可为空的日期时间

c# - 隐藏在设计模式下使用它的页面中的母版页内容

c# - 寻找有关 C# 委托(delegate)和(自定义)事件的初学者示例/教程

java - 创建一个参数为数组的泛型类

java - 结合深度泛型集合

c# - 泛型指针?

c# - 当可以在 lambda 中使用 await 时,为什么不能在 lambda 中使用 yield?