C#反思:从类型化的DataSet获取一个DataRow领域 [英] C# Reflection: Getting the fields of a DataRow from a Typed DataSet
问题描述
我目前正在建设,它接受一个对象,它是类型的方法的DataRow
从类型化的DataSet,然后在的 DataRow中字段的JSON格式(用于Web服务使用)。
通过使用的System.Reflection
,我做这样的事情:
公共字符串的getJSON(DataRow的R)
{
键入controlType = r.GetType();
的PropertyInfo [] =道具controlType.GetProperties();
的foreach(的PropertyInfo controlProperty道具)
{ }
返回;
}
然后在的foreach
语句,我会遍历各个领域并获得字段名称和值,并格式化成JSON。
问题是,遍历道具
(类型为的PropertyInfo []
),我得到的属性时我不希望被遍历:
你可以从上面的图片看,我只需要从 0的范围领域 - 11
在道具
阵列,因为那些都是这个特殊类型化的行的真正的领域。
所以我的问题是,如何能我只得到了类型化的DataRow的领域,而不是其他元数据?
[更新与解决方案]
作为<一个href=\"http://stackoverflow.com/questions/431050/c-reflection-getting-the-fields-of-a-datarow-from-a-typed-dataset#431058\">Mehrdad Afshari 的建议,而不是使用反射
,我现在用的 Table.Columns
阵列。
下面是完成的功能:
公共字符串的getJSON(DataRow的R)
{
INT索引= 0;
StringBuilder的JSON =新的StringBuilder();
的foreach(在r.Table.Columns的DataColumn项)
{
json.Append(的String.Format(\\{0} \\:\\{1} \\,item.ColumnName,R item.ColumnName]的ToString()));
如果(指数&LT; r.Table.Columns.Count - 1)
{
json.Append(,);
}
指数++;
}
回归{+ json.ToString()+};
}
你为什么不使用 row.Table.Columns
属性,而不是反映?
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).
By using System.Reflection
, I am doing something like this :
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.
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:
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.
So my question is, How can I get the fields of the Typed DataRow only, and not the other 'metadata' ?
[UPDATE with Solution]
As Mehrdad Afshari suggested, instead of using Reflection
, I am using the Table.Columns
array.
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() + "}";
}
Why don't you use row.Table.Columns
property instead of reflection?
这篇关于C#反思:从类型化的DataSet获取一个DataRow领域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!