繁体   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