我正在爲最小堆編寫泛型類,我希望能夠在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的回答最接近我認爲在這方面會有用的東西,但我擔心這並不能真正解決您的誤解。如果不明白誤解會更好,我們無法做到這一點。 –