如何判断两个对象的类型是否兼容?

发布于 2024-11-01 17:49:23 字数 287 浏览 0 评论 0原文

我有一个通用函数,我想知道如何编写。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

雪落纷纷 2024-11-08 17:49:23

你的意思是:

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

请注意,泛型在很大程度上依赖于 T(并且行为不同)可能意味着您尝试做的事情实际上并不是非常泛型......

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

羁客 2024-11-08 17:49:23
if (something.GetType() == items.GetType()) ...

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

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

This will compare the types of the actual objects.

记忆消瘦 2024-11-08 17:49:23

这个问题表述得不好,而且有点模糊,但这可能会做到这一点:

using System.Linq;

public int countItems<T>(List<T> Items)
{
    return Items.OfType<Something>().Where(thing => thisOneCounts(thing)).Count();
}

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();
}
善良天后 2024-11-08 17:49:23

我认为您想要的是使用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文