从PropertyInfo []中删除属性

时间:2011-04-01 07:05:54

标签: c# reflection

从“属性”中删除前四个属性的最简单方法是什么?其中属性是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 []集合。但是我想知道是否有任何方法可以在没有循环遍历属性的情况下实现。

谢谢

2 个答案:

答案 0 :(得分:6)

LINQ帮助:

PropertyInfo[] almostAllProperties = properties.Skip(4).ToArray();

这适用于所有类型的IEnumerables,而不仅仅是PropertyInfo的数组。


编辑:正如其他人所指出的那样,按名称排除属性更加强大。以下是使用LINQ的方法:

PropertyInfo[] almostAllProperties = properties.Where(
    p => p.Name != "ExcludeProperty1"
        && p.Name != "ExcludeProperty2"
        && p.Name != "ExcludeProperty3").ToArray();

答案 1 :(得分:1)

PropertyInfo[] filteredProperties = new PropertyInfo[properties.Length - 4];

for( int i = 4, x = 0; i < properties.Length; i++, x++ )
{
    filteredProperties[x] = properties[i];
}

就时钟周期而言,这可能是最便宜的方式,虽然没什么特别的。

除非这只是测试代码,否则您不应指望前四个属性相同。反思并不能保证顺序。