2013-06-19 69 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」...您能否給出建議如何才能實現鏈接源所需的功能? –