How do I determine whether the types of two objects are compatible?

廉价感情. 提交于 2019-12-01 09:30:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!