如何判断两个对象的类型是否兼容?
我有一个通用函数,我想知道如何编写。
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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你的意思是:
?
请注意,泛型在很大程度上依赖于 T(并且行为不同)可能意味着您尝试做的事情实际上并不是非常泛型......
do you mean:
?
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...
这将比较实际对象的类型。
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:
我认为您想要的是使用 IComparable 界面。
您可能想要使用的另一个工具是运算符重载< /a>,以便您可以定义在什么情况下两个对象相等。
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.