如何确定两个对象的类型是否兼容?

我有一个通用的function,我想知道如何写。

List something; public int countItems(List Items) { // Here I would like to compare the type of "Items" with the type of "something" to see if they are compatible. How do I do it? return 0; } 

你的意思是:

 if(typeof(T) == typeof(Something)) {...} 

请注意,generics非常依赖于T(并采取不同的行为)可能意味着您要做的事情实际上并不是非常通用的 ……

 if (something.GetType() == items.GetType()) ... 

这将比较实际对象的类型。

问题陈述不明确,而且有点模糊,但这可能会这样做:

 using System.Linq; public int countItems(List Items) { return Items.OfType().Where(thing => thisOneCounts(thing)).Count(); } 

我想你想要的是使用IComparable接口。

您可能想要使用的另一个工具是运算符重载 ,以便您可以定义两个对象在什么情况下是相等的