测试对象是否为 C# 中的泛型类型 [英] Testing if object is of generic type in C#

查看:24
本文介绍了测试对象是否为 C# 中的泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试一个对象是否是泛型类型.我尝试了以下但没有成功:

I would like to perform a test if an object is of a generic type. I've tried the following without success:

public bool Test()
{
    List<int> list = new List<int>();
    return list.GetType() == typeof(List<>);
}

我做错了什么,我该如何进行这个测试?

What am I doing wrong and how do I perform this test?

推荐答案

如果你想检查它是否是泛型类型的实例:

If you want to check if it's an instance of a generic type:

return list.GetType().IsGenericType;

如果你想检查它是否是一个通用的List:

If you want to check if it's a generic List<T>:

return list.GetType().GetGenericTypeDefinition() == typeof(List<>);

正如 Jon 所指出的,这会检查确切的类型等价性.返回 false 并不一定意味着 list 是 List 返回 false(即对象不能分配给 List<;T> 变量).

As Jon points out, this checks the exact type equivalence. Returning false doesn't necessarily mean list is List<T> returns false (i.e. the object cannot be assigned to a List<T> variable).

这篇关于测试对象是否为 C# 中的泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆