是否可以通过TypeDescriptor访问对象的索引器?

flq*_*flq 6 .net data-binding wpf typedescriptor

我很难通过TypeDescriptor获取有关对象索引器的信息 - 只是为了确定,我的意思是:

class ComponentWithIndexer
{
    public string this[int i]
    {
        get { return "hello"; }
    }
}
Run Code Online (Sandbox Code Playgroud)

由于您可以通过自定义Typedescript来影响WPF中的绑定,并且因为您可以绑定到WPF中的索引器(例如{Binding [12]),我想知道索引器的信息是否也可以通过类型描述符获得.那么,信息隐藏在哪里,如果它没有隐藏,那么WPF绑定索引器的工作原理是什么?

Jer*_*all 4

简短的回答,不 - 您无法通过以下方式访问索引器TypeDescriptor

更长的答案 -为什么你不能 - 在混乱类的深处TypeDescriptor,存在对调用的聚合属性的反射调用GetProperties。里面有这段代码:

for (int i = 0; i < properties.Length; i++)
{
    PropertyInfo propInfo = properties[i];
    if (propInfo.GetIndexParameters().Length <= 0)
    {
        MethodInfo getMethod = propInfo.GetGetMethod();
        MethodInfo setMethod = propInfo.GetSetMethod();
        string name = propInfo.Name;
        if (getMethod != null)
        {
            sourceArray[length++] = new ReflectPropertyDescriptor(type, name, propInfo.PropertyType, propInfo, getMethod, setMethod, null);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

重要的部分是检查 0 个索引参数 - 如果它有索引器,则会跳过它。:(