c# - 检查属性类型是否为 List<> 类型
问题描述
我正在尝试检查一个类的属性是否List<>
存在。
我尝试过使用IsAssignableFrom()
方法来检查它是否是一个列表。
我也尝试过使用GetInterfaces()
方法。
但两个结果都返回错误。
我的课是:
public class Product2
{
public List<ProductDetails2> ProductDetails { get; set; }
}
使用方法IsassignableFrom()
var t = typeof(Product2).GetProperties();
foreach(var p in t)
{
var isEnumerable = typeof(Enumerable).IsAssignableFrom((p.PropertyType));
}
使用方法GetInterfaces()
var t = typeof(Product2).GetProperties();
foreach(var p in t)
{
var isEnumerable = parameter.GetType().GetInterfaces().Any(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IEnumerable<>));
}
在上述两种情况下,Product2.ProductDetails 属性都为 false。
解决方案
但是为什么在这种情况下不工作
IsAssignableFrom()
?GetInterfaces()
var isEnumerable = typeof(Enumerable).IsAssignableFrom((p.PropertyType));
这不起作用,因为Enumerable
它是一个包含扩展方法的静态类IEnumerable<T>
。
您的第二个样本的概念GetInterfaces()
似乎是正确的;但是,您使用parameter
变量而不是foreach
循环变量p
,这可能是问题所在。
一旦我为此创建了几个扩展方法:
public static bool IsGenericTypeOf(this Type type, Type genericTypeDefinition)
=> type.IsGenericType && type.GetGenericTypeDefinition() == genericTypeDefinition;
public static bool IsImplementationOfGenericType(this Type type, Type genericTypeDefinition)
{
if (!genericTypeDefinition.IsGenericTypeDefinition)
return false;
// looking for generic interface implementations
if (genericTypeDefinition.IsInterface)
{
foreach (Type i in type.GetInterfaces())
{
if (i.Name == genericTypeDefinition.Name && i.IsGenericTypeOf(genericTypeDefinition))
return true;
}
return false;
}
// looking for generic [base] types
for (Type t = type; type != null; type = type.BaseType)
{
if (t.Name == genericTypeDefinition.Name && t.IsGenericTypeOf(genericTypeDefinition))
return true;
}
return false;
}
例子:
public class MyList : List<ProductDetails2> { }
//...
typeof(List<ProductDetails2>).IsGenericTypeOf(List<>); // true
typeof(MyList).IsGenericTypeOf(List<>); // false
typeof(MyList).IsImplementationOfGenericType(List<>); // true
typeof(MyList).IsImplementationOfGenericType(IEnumerable<>); // true
推荐阅读
- julia - 使用 Julia 无法在 Atom 中打开调试器窗格
- arm - 带有 std::pair 的 API
在 ARM 上从 C++14 切换到 C++17 时中断? - json - 如何正确地将新密钥传递给 JSON 字典?
- matlab - 将面顶点网格导出到 STL
- javascript - 我想在我的代码中多次调用一个函数?
- javascript - 使用 Passport.js 和 Sequelize 引用多个模型
- python - Amazon S3 boto3 如何遍历存储桶中的对象?
- java - 模拟 File.createTempFile() 并返回我们模拟的 File 对象
- java - TextView.setView() 不更新文本
- mapbox - Mapbox - 从自动完成结果中获取区域