问题
I have a generic function that I want to know how to write.
List<Something> something;
public int countItems<T>(List<T> 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;
}
回答1:
do you mean:
if(typeof(T) == typeof(Something)) {...}
?
Note that having generics depend hugely on the T (and act differently) may mean what you are trying to do isn't actually very generic...
回答2:
if (something.GetType() == items.GetType()) ...
This will compare the types of the actual objects.
回答3:
The question is poorly stated and more than a little vague, but this might do it:
using System.Linq;
public int countItems<T>(List<T> Items)
{
return Items.OfType<Something>().Where(thing => thisOneCounts(thing)).Count();
}
回答4:
I think what you want is to use the IComparable interface.
Another tool you may want to use is operator overloading, so that you can define how under what circumstances two objects are equal.
来源:https://stackoverflow.com/questions/5703356/how-do-i-determine-whether-the-types-of-two-objects-are-compatible