C# 遍历DataContract类
我有一个类,它返回一个C# 遍历DataContract类,c#,list,loops,datacontractserializer,datacontract,C#,List,Loops,Datacontractserializer,Datacontract,我有一个类,它返回一个响应2,其中只包含我关心的两个定义: Response3.Id Response3.Name 但是,此数据作为列表返回,b/c我的类定义如下所示: [DataContract] public class Response2 { [DataMember(Name = "done")] public bool done; [DataMember(Name = "records")] public List<Response3> r3
响应2
,其中只包含我关心的两个定义:
Response3.Id
Response3.Name
但是,此数据作为列表返回,b/c我的类定义如下所示:
[DataContract]
public class Response2
{
[DataMember(Name = "done")]
public bool done;
[DataMember(Name = "records")]
public List<Response3> r3entry;
}
[DataContract]
public class Response3
{
[DataMember(Name = "Id")]
public string strId { get; set; }
[DataMember(Name = "Name")]
public string strName { get; set; }
}
我得到一个错误声明:
foreach语句无法对“Response2”类型的变量进行操作,因为“Response2”不包含“GetEnumerator”的公共定义
我假设这意味着我需要在类中的DataContract中添加一些内容,但我不确定在哪里执行此操作,以便可以正确地进行迭代
有什么帮助吗?要做你想做的事(如果那确实是你想要的),你需要使用反射
foreach (var resp3 in propResponse2.r3entry)
{
System.Windows.Forms.MessageBox.Show(resp3.strName)
}
foreach (var field in propResponse2.GetType().GetFields())
{
System.Windows.Forms.MessageBox.Show(field.GetValue(propResponse2).ToString());
}
另一方面,如果您希望从所有字段获取所有[DataContract]属性,则:
foreach (DataContract dc in propResponse2.GetType()
.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.Where(m => m.GetCustomAttributes(typeof(DataContract), false).Length > 0)
.SelectMany(m => m.GetCustomAttributes(false).OfType<DataContract>()).ToArray())
{
System.Windows.Forms.MessageBox.Show(dc.Name);
}
foreach(propResponse2.GetType()中的DataContract dc)
.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.Where(m=>m.GetCustomAttributes(typeof(DataContract),false).Length>0)
.SelectMany(m=>m.GetCustomAttributes(false).OfType()).ToArray())
{
System.Windows.Forms.MessageBox.Show(dc.Name);
}
你一定来自JavaScript
世界。--我假设propResponse2
属于Response2
类型?如果是这样,那么我假设您正在尝试迭代类的数据成员foreach
不会这样做。没有这样的野兽。我假设您正在尝试序列化该类。为此,请使用DataContractSerializer
或NetDataContractSerializer
如何定义propResponse2
?@UweKeim,从错误消息中可以明显看出,它被声明为Response2
@UweKeim-我用这个有效的定义更新了这个问题,但是需要更改为resp3.strName
,那么遍历此列表的缺点是什么?我不知道为什么反射不好,而从所有字段获取所有属性是好的?问题不是我只想要“一些”属性,而是这被定义为一个列表,所以列表中有许多“集合”这些属性,我想遍历这些单独的项目。@gotmike:我没有说反射是坏的。我只是不知道你想要什么。您想要propResponse2
字段的值,还是想要DataContract.Name
值?反射确实比编译时访问慢,但反射在C#中得到了优化。“问题”在于,如果这是一段需要大量执行的代码,那么反射就是一个性能问题。
foreach (DataContract dc in propResponse2.GetType()
.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.Where(m => m.GetCustomAttributes(typeof(DataContract), false).Length > 0)
.SelectMany(m => m.GetCustomAttributes(false).OfType<DataContract>()).ToArray())
{
System.Windows.Forms.MessageBox.Show(dc.Name);
}