带有where子句的泛型所需的显式强制转换

时间:2014-02-20 10:09:07

标签: 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) {}
    }

  }

1 个答案:

答案 0 :(得分:4)

您需要在class类的T类型参数上添加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