【问题标题】:How do I loop through the sub property of a class?如何循环遍历类的子属性?
【发布时间】:2012-07-05 00:52:25
【问题描述】:

我有一个客户端类,其中一个属性是电子邮件,它是一个字符串列表。我可以循环遍历类的属性以输出值,但是当它到达 Emails 属性时,它不会循环遍历电子邮件,因为它需要对列表进行另一个循环。

foreach (PropertyInfo prop in oClient.GetType().GetProperties())
{
    if (prop.Name.ToUpper().ToString() == "EMAILS")
    {
        //need code to loop through emails
    }
    else
    {
        Response.Write("<b>" + prop.Name.ToString() + "</b>: " + prop.GetValue(oClient, null) + "<br />");
    }
}

【问题讨论】:

  • 电子邮件属于哪种类型,List?你可以转换它,比如 ((Listprop).ForEach(x => "" + x + "">)
  • 我开始走 foreach(string str in prop) 的路线,但它引发了一个错误。然后我尝试了谷歌,找不到任何足够具体的东西。于是我来到了这里。
  • @Curtis:Emails 是一个集合吗?
  • 这是一个列表...public List Emails { get;放; }
  • 那么@Rup 的答案可能就是你所需要的。

标签: c# list loops reflection properties


【解决方案1】:

您可以使用读取电子邮件的值

Object emails = prop.GetValue(oClient, null);

然后遍历它,例如

IEnumerable<String> emailsEnumerable = emails as IEnumerable<String>;
if (emailsEnumerable != null) {
    foreach(string emailValue in emailsEnumerable) {
        // ...
    }
}

【讨论】:

    猜你喜欢
    • 2015-08-09
    • 1970-01-01
    • 2023-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-16
    • 1970-01-01
    • 2016-05-26
    相关资源
    最近更新 更多