2013-06-19 65 views
1

目的是为索引/非索引属性编写通用属性路径检索器。 对于索引,只能考虑数字指标。索引/非索引属性的通用属性路径检索器

我有以下代码。这应该基于属性路径检索属性,甚至索引属性。 我尝试在MyObject上使用它,它的Data属性是DataTable。 propertyPath将是例如Data.Rows [0] 当执行到达该注释线,System.Reflection.TargetParameterCountException抛出话说

参数数量不匹配。

public static object GetPropertyPathValue(object value, string propertyPath) 
    { 
     object propValue = value; 
     foreach (string propName in propertyPath.Split('.')) 
     { 
      string propName2 = propName; 
      object[] index = null; 
      int bracket1 = propName2.IndexOf("["); 
      int bracket2 = propName2.IndexOf("]"); 
      if ((-1 < bracket1) && (-1 < bracket2)) 
      { 
       index = new object[] { Int32.Parse(propName2.Substring(bracket1 + 1, bracket2 - bracket1 - 1)) }; 
       propName2 = propName2.Substring(0, bracket1); 
      } 
      PropertyInfo propInfo = propValue.GetType().GetProperty(propName2); 
      propValue = propInfo.GetValue(propValue, index); // Exception thrown here 
     } 
     return propValue; 
    } 

我检查这个(PropertyInfo.GetValue() - how do you index into a generic parameter using reflection in C#?),但便无法找到答案,我的问题:我在做什么错?

回答

2

我的开源项目Xoml的代码完全符合您的需求。看看this特定的源文件。

另外 - 我认为你无法找到该属性的原因是因为默认索引器称为“项目”。看看第116行。

+0

不错。你的项目到底做了什么?我的意思是它使用XAML来做什么? –

+0

谢谢:)它不使用XAML,它以线程安全和高效的方式重现了XAML的功能。我开发/使用它用于大量数据驱动的图形渲染应用程序。 – Ani

+0

谢谢。链接源116行没有提及“Item”...您能否给出建议如何才能实现链接源所需的功能? –