C# 比较泛型类型
我正在写一个通用的二叉搜索树。我需要比较两种泛型类型。假设用户已经在T类中实现了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 <
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有点生疏;)