Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 比较泛型类型_C#_Generics - Fatal编程技术网

C# 比较泛型类型

C# 比较泛型类型,c#,generics,C#,Generics,我正在写一个通用的二叉搜索树。我需要比较两种泛型类型。假设用户已经在T类中实现了IComparable,那么该如何做呢 private void Insert(T newData, ref Node<T> currentRoot) { if (currentRoot == null) { currentRoot = new Node<T>(newData); return; } if (newData <

我正在写一个通用的二叉搜索树。我需要比较两种泛型类型。假设用户已经在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); 
}
private void Insert(T newData,ref Node currentRoot)
{
if(currentRoot==null)
{
currentRoot=新节点(newData);
回来
}

如果(newData您必须向方法添加一个通用约束,其中T:IComparable
,以使该方法可用于您类型的实例
T

private void Insert(T newData, ref Node<T> currentRoot) where T: IComparable<T>
{
  //...
}
private void Insert(T newData,ref Node currentRoot),其中T:IComparable
{
//...
}
然后您可以使用:

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

if(newData.CompareTo(currentRoot.data)您必须向方法添加一个通用约束
其中T:IComparable
,以使该方法可用于您类型的实例
T

private void Insert(T newData, ref Node<T> currentRoot) where T: IComparable<T>
{
  //...
}
private void Insert(T newData,ref Node currentRoot),其中T:IComparable
{
//...
}
然后您可以使用:

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

if(newData.CompareTo(currentRoot.data)使用
where
子句,即

class Node<T> where T : IComparable
类节点,其中T:IComparable

使用
where
子句,即

class Node<T> where T : IComparable
类节点,其中T:IComparable

newData.CompareTo(currentRoot.data)
work?仅适用于@BrokenGlass指出的
其中t:IComparable
newData.CompareTo(currentRoot.data)
work?仅适用于
where T:IComparable
,正如@BrokenGlass指出的,这个答案是不完整的,仅仅提供一个约束不允许用户尝试的代码行。幸运的是,BrokenGlass添加了一个合适的示例解决方案。我明白了。我的C有点生锈了。)这个答案是不完整的,仅仅提供一个约束不允许用户尝试的代码行。幸运的是,BrokenGlass添加了一个合适的示例解决方案。我明白了。我的C有点生疏;)