簡體   English   中英

C#反射:從類型化數據集中獲取DataRow的字段

[英]C# Reflection: Getting the fields of a DataRow from a Typed DataSet

我目前正在構建一個方法,從類型化的DataSet中獲取DataRow類型的對象,然后返回DataRow中字段的JSON格式的字符串(用於Web服務)。

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

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

        }
        return "";
    }

然后在foreach語句中,我將迭代每個字段並獲取字段名稱和值,並將其格式化為JSON。


問題是當迭代props (類型為PropertyInfo[] )時,我得到的屬性我不想被迭代:

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

從上圖中可以看出,我只需要props數組中0 - 11的字段,因為這些是這個特定類型行的“真實字段”。

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


[更新解決方案]

正如Mehrdad Afshari建議的那樣,我使用的是Table.Columns數組,而不是使用Reflection

這是完成的功能:

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() + "}";
}

為什么不使用row.Table.Columns屬性而不是反射?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM