我正在写最小堆在那里我希望能够heapify一个泛型类TKey
以及T
。
interface IHeap<T, TKey>
where TKey : IComparable<TKey>
{
void Insert(T x);
T Delete();
T Top();
}
public class MinHeap<T, TKey> : IHeap<T, TKey>
where TKey : IComparable<TKey>
{
public MinHeap(int capacity)
: this(capacity, x => x) // <---- compilation error here
{ }
public MinHeap(int capacity, Func<T, TKey> keySelector)
: this(capacity, keySelector, Comparer<TKey>.Default)
{ }
public MinHeap(int capacity, Func<T, TKey> keySelector, IComparer<TKey> comparer)
{
// ...
}
// ...
}
我收到以下编译错误x => x
:
Cannot convert lambda expression to delegate type 'System.Func<T,TKey>' because some of the return types in the block are not implicitly convertible to the delegate return type.
Cannot implicitly convert type 'T' to 'TKey'
我如何做到这一点并且只有一堂课?
更新:
我希望能够做两件事:
// 1
var minheap = new MinHeap<Person, int>(10, x => x.Age);
// 2
var minheap = new MinHeap<int>(10);
// instead of
var minheap = new MinHeap<int, int>(10, x => x);
MinHeap<T,TKey>
可以使用与约束匹配的任何通用类型参数实例化。
例如,这意味着您可以使用MinHeap<string,int>
。在这种情况下,你会尝试指派拉姆达x => x
到Func<string,int>
这是行不通的,因为它是一个Func<string,string>
。
我认为没有一种明智的方法来实现您想要的目标,因为没有一种很好的方法可以将“任意”类型转换为另一种任意类型,这正是您所需要的。
您可以做的是删除此构造函数,并添加一个静态构造函数,该构造函数可用于T
和TKey
类型相同的情况:
public static class MinHeap
{
public static MinHeap<T,T> Create<T>(int capacity) where T : IComparable<T>
{
return new MinHeap<T,T>(capacity, x => x);
}
}
但是,如果这还不足以满足您的需求,那么只需删除构造函数,并接受人们必须自己处理lambda的问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句