简体   繁体   English

C#反射:从类型化数据集中获取DataRow的字段

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

I am currently building a method that takes an object that is of type DataRow from a typed DataSet, and then returning a string in JSON format of the fields in the DataRow (for use in a Web Service). 我目前正在构建一个方法,从类型化的DataSet中获取DataRow类型的对象,然后返回DataRow中字段的JSON格式的字符串(用于Web服务)。

By using System.Reflection , I am doing something like this : 通过使用System.Reflection ,我正在做这样的事情:

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

        }
        return "";
    }

And then in the foreach statement, I would iterate every field and get the field name and value, and format it into JSON. 然后在foreach语句中,我将迭代每个字段并获取字段名称和值,并将其格式化为JSON。


The problem is that when iterating over the props (of type PropertyInfo[] ), I am getting properties that I do not want to be iterated over: 问题是当迭代props (类型为PropertyInfo[] )时,我得到的属性我不想被迭代:

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

As you can see from the above image, I only need the fields that range from 0 - 11 in the props array, because those are the 'real fields' of this particular typed row. 从上图中可以看出,我只需要props数组中0 - 11的字段,因为这些是这个特定类型行的“真实字段”。

So my question is, How can I get the fields of the Typed DataRow only, and not the other 'metadata' ? 所以我的问题是, 我怎样才能获得Typed DataRow的字段,而不是其他'元数据'?


[UPDATE with Solution] [更新解决方案]

As Mehrdad Afshari suggested, instead of using Reflection , I am using the Table.Columns array. 正如Mehrdad Afshari建议的那样,我使用的是Table.Columns数组,而不是使用Reflection

Here is the completed function: 这是完成的功能:

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