簡體   English   中英

比較通用類型

[英]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

http://msdn.microsoft.com/zh-CN/library/bb384067.aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM