[英]Comparing generic types
我正在編寫通用二進制搜索樹。 我需要比較兩種通用類型。 假設用戶已經在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);
}
您必須在方法中添加where T: IComparable<T>
的通用約束where T: IComparable<T>
以使CompareTo()
方法可用於類型T
實例。
private void Insert(T newData, ref Node<T> currentRoot) where T: IComparable<T>
{
//...
}
然后,您可以使用:
if (newData.CompareTo(currentRoot.data) <= 0)
{
//...
}
使用where
子句,即
class Node<T> where T : IComparable
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.