如果测试的对象是通用型的C# [英] Testing if object is of generic type in C#

查看:249
本文介绍了如果测试的对象是通用型的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;

如果您要检查它是否是一个普通的名单,其中,T&GT;

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

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

正如乔恩所指出的,这个检查的确切类型等价。返回不一定意味着列表清单&LT; T&GT; 返回(即对象不能被分配​​到一个名单,其中,T&GT; 变量)。

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天全站免登陆