将双精度数组转换为 IComparable 数组
我正在尝试使用 VB.NET 创建一个 Quicksort 基类,并将其作为 IComparable 元素的数组。 签名看起来像这样:
public shared sub Sort(ByVal values() as IComparable)
但是,当我传递一个双精度数组时,编译器给出了错误。
Dim numbers(100) as double
Dim random as new Random(0)
for i as integer = 0 to numbers.length - 1
numbers(i) = random.NextDouble()
Next
QuickSort.Sort(numbers) ' gives compiler error.
错误是:
Error 88 Value of type '1-dimensional array of Double' cannot be converted to '1-dimensional array of System.IComparable' because 'Double' is not derived from 'System.IComparable'. C:\Proving Grounds\Module1.vb
.NET 文档指出 double 实现了 IComparable。 为什么 .NET 编译器不允许我这样做?
I'm trying to create a Quicksort base class using VB.NET, taking it an array of IComparable elements. The signature looks like this:
public shared sub Sort(ByVal values() as IComparable)
However, when I pass in an array of doubles, the compiler is giving me errors.
Dim numbers(100) as double
Dim random as new Random(0)
for i as integer = 0 to numbers.length - 1
numbers(i) = random.NextDouble()
Next
QuickSort.Sort(numbers) ' gives compiler error.
The error is:
Error 88 Value of type '1-dimensional array of Double' cannot be converted to '1-dimensional array of System.IComparable' because 'Double' is not derived from 'System.IComparable'. C:\Proving Grounds\Module1.vb
The .NET documentation states that double's implement IComparable. Why isn't the .NET compiler letting me do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
虽然
double
可以转换为IComparable
,但这并不意味着double[]
可以转换为IComparable[]. 一个简单的选择是创建一个新的
IComparable[]
数组并复制数据 - 或者在您的情况下,只需将原始数组启动为IComparable[]
即可。实际上,我很想使用通用的
IComparable
或IComparer
接口,或Comparison
委托- 全部使用泛型 - 这也允许使用Comparer.Default
和非默认比较器。Although
double
can be cast toIComparable
, it doesn't mean thatdouble[]
can be cast toIComparable[]
. A simple option would be to create a newIComparable[]
array and copy the data over - or in your case, simply start the original array asIComparable[]
.Actually, I'd be tempted to use the generic
IComparable<T>
orIComparer<T>
interfaces, or theComparison<T>
delegate - all using generics - this also allows use ofComparer<T>.Default
and non-default comparers.