C#反射:从类型化数据集中获取数据行的字段
我目前正在构建一个方法,该方法从类型化数据集中获取类型为C#反射:从类型化数据集中获取数据行的字段,c#,asp.net,reflection,strongly-typed-dataset,datarow,C#,Asp.net,Reflection,Strongly Typed Dataset,Datarow,我目前正在构建一个方法,该方法从类型化数据集中获取类型为DataRow的对象,然后以DataRow中字段的格式返回字符串(用于Web服务) 通过使用System.Reflection,我正在做这样的事情: public string getJson(DataRow r) { Type controlType = r.GetType(); PropertyInfo[] props = controlType.GetProperties();
DataRow
的对象,然后以DataRow中字段的格式返回字符串(用于Web服务)
通过使用System.Reflection
,我正在做这样的事情:
public string getJson(DataRow r)
{
Type controlType = r.GetType();
PropertyInfo[] props = controlType.GetProperties();
foreach (PropertyInfo controlProperty in props)
{
}
return "";
}
然后在foreach
语句中,我将迭代每个字段,获得字段名和值,并将其格式化为JSON
问题是,在迭代
道具
(类型为PropertyInfo[]
)时,我得到了不希望迭代的属性:
如上图所示,我只需要props
数组中0-11
范围内的字段,因为这些字段是这个特定类型行的“真实字段”
因此,我的问题是,如何仅获取类型化数据行的字段,而不获取其他“元数据”?
[使用解决方案更新] 正如所建议的,我使用的不是
反射
,而是表.Columns
数组
以下是已完成的功能:
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() + "}";
}
公共字符串GetJson(DataRow r)
{
int指数=0;
StringBuilder json=新的StringBuilder();
foreach(r.Table.Columns中的DataColumn项)
{
Append(String.Format(“\”{0}\”:\“{1}\”,item.ColumnName,r[item.ColumnName].ToString());
如果(索引
为什么不使用行.Table.Columns
属性而不是反射