【问题标题】:C# Reflection: Getting the fields of a DataRow from a Typed DataSetC# 反射:从 Typed DataSet 中获取 DataRow 的字段
【发布时间】:2010-09-30 16:06:03
【问题描述】:

我目前正在构建一个方法,该方法从类型化的 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() + "}";
}

【问题讨论】:

    标签: c# asp.net reflection strongly-typed-dataset datarow


    【解决方案1】:

    为什么不使用row.Table.Columns 属性而不是反射?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-09
      • 2011-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-06
      相关资源
      最近更新 更多