我正在为最小堆编写泛型类,我希望能够在TKey
以及T
上堆积。无法将lambda表达式转换为委托类型'System.Func <T,TKey>'
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);
编译器错误很清楚为什么代码无效。你的问题是不清楚你为什么认为这样的代码应该工作。泛型的要点是提供编译时类型安全性,但考虑到当前的声明,不可能在编译时确保该表达式的类型安全。请更好地解释你的想法。 –
我想在个人财产('TKey')的Person.Age上堆人Person []。我也想在int []('T')上堆砌。 – hIpPy
想做点事不是一个解释。我希望我的C#编译器每次编译我的程序时都会给我一个巧克力薄荷,但是我没有任何问题想问我如何才能做到这一点。据了解,这是不可能的。同样,你要求编译器做一些根本不可能的事情。请解释_为什么你认为这应该是可能的。 Ben的回答最接近我认为在这方面会有用的东西,但我担心这并不能真正解决您的误解。如果不明白误解会更好,我们无法做到这一点。 –