2009-01-10 43 views
2

我目前正在構建一種方法,它從類型化數據集中獲取類型爲DataRow的對象,然後返回DataRow中字段格式爲JSON的字符串(用於Web服務)。C#反射:從類型化數據集中獲取DataRow的字段

通過使用System.Reflection,我做這樣的事情:

public string getJson(DataRow r) 
    { 
     Type controlType = r.GetType(); 
     PropertyInfo[] props = controlType.GetProperties(); 
     foreach (PropertyInfo controlProperty in props) 
     { 

     } 
     return ""; 
    } 

然後在foreach聲明,我會遍歷各個領域,並獲得字段名稱和值,並格式化成JSON。


的問題是,遍歷(的PropertyInfo[]型),我不想,我得到屬性props時要遍歷:

alt text http://img88.imageshack.us/img88/2001/datarowreflectionht0.gif

正如你可以看到上面的圖片中,我只需要範圍從0 - 11props數組的字段,因爲這些是這個特定類型行的「真實字段」。

所以我的問題是,我怎樣才能得到Typed DataRow的字段,而不是其他'元數據'?


[UPDATE用溶液]

Mehrdad Afshari作爲建議的,而不是使用Reflection,我使用的Table.Columns陣列。

這是填好的功能:

public string GetJson(DataRow r) 
{ 
    int index = 0; 
    StringBuilder json = new StringBuilder(); 
    foreach (DataColumn item in r.Table.Columns) 
    { 
     json.Append(String.Format("\"{0}\" : \"{1}\"", item.ColumnName, r[item.ColumnName].ToString())); 
     if (index < r.Table.Columns.Count - 1) 
     { 
      json.Append(", "); 
     } 
     index++; 
    } 
    return "{" + json.ToString() + "}"; 
} 

回答

11

你爲什麼不使用row.Table.Columns屬性,而不是反映?

相關問題