2011-09-23 84 views
1

我正在編寫通用二進制搜索樹。我需要比較兩種泛型類型。如何做到這一點,假設用戶在T類中實現了IComparable比較通用類型

private void Insert(T newData, ref Node<T> currentRoot) 
{ 
    if (currentRoot == null) 
    { 
     currentRoot = new Node<T>(newData); 
     return; 
    } 
    if (newData <= currentRoot.data) //doesn't work, need equivalent functionality 
     Insert(newData, ref currentRoot.lChild); 
    else 
     Insert(newData, ref currentRoot.rChild); 
} 
+0

不'newData.CompareTo(currentRoot.data)'工作? –

+0

只能用'where T:IComparable '作爲@BrokenGlass指出的 – devnull

回答

6

你必須通用約束where T: IComparable<T>添加到您的方法來提供給您的T類型的實例CompareTo()方法。

private void Insert(T newData, ref Node<T> currentRoot) where T: IComparable<T> 
{ 
    //... 
} 

然後你可以使用:

if (newData.CompareTo(currentRoot.data) <= 0) 
{ 
    //... 
} 
+0

拍攝時,你更快 –

+0

@BrokenGlass謝謝,那有效。 – devnull

1

使用where條款,即

class Node<T> where T : IComparable 

http://msdn.microsoft.com/en-us/library/bb384067.aspx

+0

這個答案是不完整的,只是提供一個約束不允許用戶嘗試的代碼行。幸運的是,BrokenGlass添加了一個合適的示例解決方案。 –

+0

我明白了。我的C#有點生疏;) –