遍历 DataContract class

Iterating through DataContract class

我有一个 class 那个 returns 一个 Response2 其中只有两个我关心的定义:

Response3.Id
Response3.Name

但是,此数据作为列表返回,b/c 我的 class 定义如下所示:

[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; }
}

现在我有一个要遍历的字符串列表,但是当我尝试执行以下操作时:

Response2 propResponse2 = MakeRequest2(propertyRequest2, sfToken);

foreach (string strId in propResponse2)
{
    System.Windows.Forms.MessageBox.Show(strId.Name)
}

我收到一条错误消息:

foreach statement cannot operate on variables of type 'Response2' because 'Response2' does not contain a public definition for 'GetEnumerator'

我认为这意味着我需要向 class 中的 DataContract 添加一些内容,但我不确定在何处执行此操作以便我可以正确迭代。

有什么帮助吗?

foreach (var resp3 in propResponse2.r3entry)
{
    System.Windows.Forms.MessageBox.Show(resp3.strName)
}

做你想做的事(如果那确实是你想要的)你需要使用 reflection

        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);

}