从“properties”中删除前四个属性的最简单方法是什么?其中属性是PropertyInfo集合,如下所示。
PropertyInfo[] properties = GetAllPropertyForClass(className);
public static PropertyInfo[] GetAllPropertyForClass(string className) {
Type[] _Type = Assembly.GetAssembly(typeof(MyAdapter)).GetTypes();
return _Type.SingleOrDefault(
t => t.Name == className).GetProperties(BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
}当然,我可以遍历并构建另一个PropertyInfo[]集合,方法是忽略基于其索引或名称的属性。但我想知道是否有任何方法可以在不遍历属性的情况下实现。
谢谢
发布于 2011-04-01 15:07:22
LINQ帮助:
PropertyInfo[] almostAllProperties = properties.Skip(4).ToArray();这不仅适用于PropertyInfo数组,还适用于所有类型的IEnumerables。
编辑:正如其他人所指出的,按名称排除属性更健壮。下面是你如何使用LINQ做到这一点:
PropertyInfo[] almostAllProperties = properties.Where(
p => p.Name != "ExcludeProperty1"
&& p.Name != "ExcludeProperty2"
&& p.Name != "ExcludeProperty3").ToArray();发布于 2011-04-01 15:17:13
PropertyInfo[] filteredProperties = new PropertyInfo[properties.Length - 4];
for( int i = 4, x = 0; i < properties.Length; i++, x++ )
{
filteredProperties[x] = properties[i];
}就时钟周期而言,这可能是最便宜的方法,尽管没有什么花哨的东西。
除非这只是测试代码,否则您不应该指望前四个属性是相同的。反射不能保证序列。
https://stackoverflow.com/questions/5510156
复制相似问题