从类中获取PropertyInfo [],省略索引器方法

时间:2015-07-08 17:47:14

标签: c# class properties

我在类中有一个索引器方法,允许我这样做:

var foo = Class["bar"];
Class["bar"] = foo;

这是:

public object this[string propertyName]
{
    get { return this.GetType().GetProperty(propertyName).GetValue(this, null); }
    set { this.GetType().GetProperty(propertyName).SetValue(this, value, null); }
}

我想得到一个PropertyInfo []数组并循环遍历它以获取属性的值。但是这个扩展方法(类型System.Object)正在数组中出现,我不知道如何排除它。

我可以在循环中排除它。但如果我的班级 包含“Item”属性,则可能会出现问题。有什么想法吗?

PropertyInfo[] properties = typeof(Class).GetProperties();
foreach(var prop in properties)
    if(prop.name == "Item")
        continue;

enter image description here

2 个答案:

答案 0 :(得分:3)

您可以使用PropertyInfo.GetIndexParameters()方法确定属性是否为索引器:

PropertyInfo[] properties = typeof(Class).GetProperties();
foreach(var prop in properties)
    if(prop.GetIndexParameters().Length > 0)  // it is an indexer
        continue;

如果方法返回非空数组,则它是索引器。这样您就不必依赖编译器生成的默认名称Item,除非被属性覆盖。

答案 1 :(得分:1)

您可以检查IndexParameters的数量,如果超过0,则将其排除。

foreach(var prop in typeof(Class).GetProperties()
    .Where (x => x.GetIndexParameters().Length <= 0))
{        
    if(prop.name == "Item")
        continue;
}
相关问题