gpt4 book ai didi

c# - 比较通用类型

转载 作者:太空宇宙 更新时间:2023-11-03 18:42:22 24 4
gpt4 key购买 nike

我正在编写通用二叉搜索树。我需要比较两个通用类型。如何做到这一点,假设用户已经在 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>用你的方法制作 CompareTo() 可用于您的类型的实例的方法 T .

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

然后你可以使用:

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

关于c# - 比较通用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7534869/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com