我希望有人可以建议一种方法来避免对下面的“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) {}
}
}
最佳答案
您需要添加 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
虽然两者都是Int32
和 String
实现 IConvertible
.
参见 Why covariance and contravariance do not support value type .
关于c# - 通用 with where 子句需要显式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21904508/