[英]Is there a way to find out whether a generic type is integer and count all elements inside the collection that are even
我為二叉搜索樹編寫了通用的 class,我需要定義一個方法來搜索樹中的所有偶數。 這是我定義樹的方式:
class BST<T> : ICollection<T> where T : IComparable<T> {
public int CountEven() {
if (root != null) return ccount(root, 2);
return 0;
}
private int ccount(Node root, int div) {
Type itemType = typeof(T);
if (itemType == typeof(int) && root != null) {
if (root.data % div == 0) {
//error: operation / cannot be applied to operands of type T and int
return 1 + ccount(root.left, div) + ccount(root.right, div);
}
else { return ccount(root.left, div) + ccount(root.right, div); }
}
return 0;
}
}
為避免錯誤,您可以調整 if 語句:
if (itemType == typeof(int) && root?.data is int intData)
之后,您可以使用 int 類型的變量intData
。
另外,我猜您使用了錯誤的運算符進行偶數檢查。 你應該使用類似的東西:
if (intData % div == 0)
結合您的ccount()
方法應該類似於:
private int ccount(Node root, int div)
{
Type itemType = typeof(T);
if (itemType == typeof(int) && root?.data is int intData)
{
if (intData % div == 0)
{
return 1 + ccount(root.left, div) + ccount(root.right, div);
}
else
{
return ccount(root.left, div) + ccount(root.right, div);
}
}
return 0;
}
public int CountEven()
{
if (root != null)
return ccount(root, 2);
return 0;
}
private int ccount(Node root, int div)
{
Type itemType = typeof(T);
if (root == null)
return 0;
if ( itemType == typeof(int) && root.data is int intData)
{
int add = 0;
if (intData % div == 0)
add = 1;
return add+ ccount(root.left, div) + ccount(root.right, div);
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.