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

流过昼夜 提交于 2019-12-01 10:49:47

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...

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

This will compare the types of the actual objects.

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();
}

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.

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