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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/431050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 03:07:00  来源:igfitidea点击:

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

c#asp.netreflectionstrongly-typed-datasetdatarow

提问by Andreas Grech

I am currently building a method that takes an object that is of type DataRowfrom a typed DataSet, and then returning a string in JSONformat of the fields in the DataRow (for use in a Web Service).

我目前正在构建一个方法,该方法DataRow从类型化的 DataSet 中获取一个类型的对象,然后以JSON格式返回DataRow 中字段的字符串(用于 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 foreachstatement, 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

替代文字 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 - 11in the propsarray, because those are the 'real fields' of this particular typed row.

你可以从上面的图片看,我只需要,范围从田野0 - 11props数组,因为这些都是这个特殊类型化的行的“真正的领域”。

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 Afsharisuggested, instead of using Reflection, I am using the Table.Columnsarray.

正如Mehrdad Afshari建议的那样Reflection,我没有使用,而是使用Table.Columns数组。

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

采纳答案by Mehrdad Afshari

Why don't you use row.Table.Columnsproperty instead of reflection?

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