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

Get PropertyInfo[] from a class, leaving out indexer method

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

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)正在数组中出现,我不知道如何排除它。

我可以在我的循环中排除它。但如果我的 class 确实 包含 "Item" 属性,则可能会有问题。有什么想法吗?

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

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

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

如果方法 returns 是一个非空数组,那么它就是一个索引器。这样你就不必依赖编译器生成的默认名称 Item 除非被属性覆盖。

可以查看IndexParameters个数,如果大于0则排除

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