[英]How to write in a less cumbersome way an extension method for generic Interface with a constraint
interface interface1<Coordinate> where Coordinate : IComparable<Coordinate>
{
Coordinate getPosition(XYZ p);
}
static class CreateOrderOnASpaceExtensions
{
public static IOrderedEnumerable<T> OrderElements<Coordinate, T>(this interface1<Coordinate> myInterface, IEnumerable<T> elements, Func<T, XYZ> elementToPoint)
where Coordinate : IComparable<Coordinate>
=>
elements.OrderBy(
x => myInterface.getPosition(elementToPoint(x)),
Comparer<Coordinate>.Create((x, y) => x.CompareTo(y)
)
);
}
Should I really write where Coordinate: IComparable<Coordinate>
in the extension method declaration?我真的应该在扩展方法声明中写
where Coordinate: IComparable<Coordinate>
吗?
I already said that Coordinate
is comparable when I created interface1
.我在创建
interface1
时已经说过Coordinate
是可比较的。
Without that:没有那个:
There is no boxing convertion or type paramater convertion from Coordinate to Comparable
没有从 Coordinate 到 Comparable 的装箱转换或类型参数转换
I'll use ===
to show to which part the where
applies in each of your generic definitions:我将使用
===
来显示在您的每个通用定义where
适用于哪个部分:
interface interface1<Coordinate>
==========
where Coordinate : IComparable<Coordinate>
{
...
}
and和
static class CreateOrderOnASpaceExtensions
{
public static IOrderedEnumerable<T> OrderElements<Coordinate, T>(this interface1<Coordinate> myInterface, IEnumerable<T> elements, Func<T, XYZ> elementToPoint)
==========
where Coordinate : IComparable<Coordinate>
}
Without the 2nd where
, the compiler will see that you are trying to feed an unconstrained type Coordinate
(which could then be anything) into interface1<>
, which has a constraint , making the unconstrained Coordinate
not allowed.如果没有第二个
where
,编译器会看到您正在尝试将不受约束的类型Coordinate
(然后可以是任何东西)输入interface1<>
,它有一个 constraint ,使得不受约束的Coordinate
是不允许的。
The fact that interface1
has a constraint does not mean that the "world" outside of it will magically also be restricted if you try to connect it; interface1
具有约束的事实并不意味着如果您尝试连接它,它之外的“世界”也会神奇地受到限制; it already needs to fit before it can be allowed.它已经需要适应才能被允许。
An analogy: you made a railroad which requires trains.打个比方:你建造了一条需要火车的铁路。 You first need to make a train, and then you can put in on the railroad.
您首先需要制作火车,然后您可以放入铁路。 There's no magic that makes any vehicle that you put on it a train.
没有任何魔法可以让你装上的任何车辆成为火车。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.