如何比较泛型类型?

nul*_*Dev 24 c# generics

我有一个类,它有一些类型的属性List<float>,List<int>等等.现在我通过反射查询这个类的属性,以便我得到一个列表PropertyInfo.

我想过滤类型的类型List<>.但比较

propertyInfo.PropertyType == typeof(List<>)
Run Code Online (Sandbox Code Playgroud)

失败.

我可以通过比较名称来解决这个问题,即以下比较工作:

propertyInfo.PropertyType.Name == typeof(List<>).Name
Run Code Online (Sandbox Code Playgroud)

我认为应该有一种更好的方法来比较Generic类型.有线索吗?

Jon*_*eet 51

您可以使用:

Type type = propertyInfo.PropertyType;
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
{
    ...
}
Run Code Online (Sandbox Code Playgroud)