我试图处理具有属性的泛型类List<T>.但是在使用时检查属性时它不起作用IsAssignableFrom.
代码片段:
var type = model.GetType();
var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
int colorIndex = 0;
foreach (var property in properties)
{
if (typeof(List<>).IsAssignableFrom(property.PropertyType))
{
//codes here
}
}
Run Code Online (Sandbox Code Playgroud)
我在这里错过了什么吗?为什么它不将列表视为列表,即使它是列表?
在您的model对象中,您具有特定类型的属性,例如List<string>,List<int>或类似的东西.我是你的代码但是你正在测试开放泛型类型.这些类型不一样,因此您不会在if语句中获得匹配.要解决此问题,您应该使用函数GetGenericTypeDefinition()来获取基础开放泛型类型:
foreach (var property in properties)
{
if (property.PropertyType.IsGenericType &&
typeof(List<>).IsAssignableFrom(property.PropertyType.GetGenericTypeDefinition()))
{
//codes here
}
}
Run Code Online (Sandbox Code Playgroud)