我试图找出类型的集合是否IEnumerable
包含属性.
假设RowModels
是一个类型的集合IEnumerable
,我有......
foreach (var items in RowModels) {
if (items.GetType()
.GetProperties()
.Contains(items.GetType().GetProperty("TRId").Name) )
{
// do something...
}
}
Run Code Online (Sandbox Code Playgroud)
我收到了错误
System.Reflection.PropertyInfo[] does not contain a definition for 'Contains'
and the best extension method overload has some invalid arguments.
Run Code Online (Sandbox Code Playgroud)
你可以使用Enumerable.Any()
:
foreach (var items in RowModels) {
if(items.GetType().GetProperties().Any(prop => prop.Name == "TRId") )
{
// do something...
}
}
Run Code Online (Sandbox Code Playgroud)
话虽这么说,您也可以直接检查酒店:
foreach (var items in RowModels) {
if(items.GetType().GetProperty("TRId") != null)
{
// do something...
}
}
Run Code Online (Sandbox Code Playgroud)
此外 - 如果您正在寻找RowModels
实现特定接口或某些特定类的项目,您可以写:
foreach (var items in RowModels.OfType<YourType>())
{
// do something
}
Run Code Online (Sandbox Code Playgroud)
该OfType<T>()
方法将自动过滤到指定类型的类型.这样做的好处是可以为您提供强类型变量.