使用反射遍历嵌套在Object中的Object List

本文关键字:Object 中的 List 嵌套 反射 遍历 | 更新日期: 2023-09-27 18:12:22

我正试图生成一个基于表单输入的电子邮件,使用反射使电子邮件更快,希望更好的方式。

遍历Company对象中的嵌套列表,使_body是Company及其嵌套对象列表(AsnContact)中所有属性的长输出列表。

当方法接受Company对象时,它遍历Company中的每个属性并检查它是什么类型。我在检查List<>的类型时出错了,我不知道为什么它不在集合中迭代。

我整个上午都在摆弄代码,但似乎没有任何进展。

我哪里错了?

基本模型结构:

public class Company {
public string name {get;set;}
public List<Asn> asns {get;set;}
public List<Contact> contacts {get;set;}
}
public class Asn {
// string/int/bool properties
}
public class Company {
// string/int/bool properties
}

问题方法代码:

    public static void SendEmail(Company cm)
        {
                string _body = "";
                string _subject = "ASN Form Request";
                Type type = cm.GetType();
                Type type2 = cm.asns.GetType();
                Type type3 = cm.contacts.GetType();
                PropertyInfo[] companyProperties = type.GetProperties();
                PropertyInfo[] asnProperties = type2.GetProperties();
                PropertyInfo[] contactProperties = type3.GetProperties();
                foreach(PropertyInfo property in companyProperties)
                {
                    if (property.PropertyType == typeof(string) || property.PropertyType == typeof(int) || property.PropertyType == typeof(bool))
                    _body += property.Name + " = " + property.GetValue(cm, null) + Environment.NewLine;
                    if (property.PropertyType == typeof(List<>)) // not running through the model properties
                        foreach(PropertyInfo asnproperty in asnProperties)
                        {
                            _body += asnproperty.Name + " = " + asnproperty.GetValue(cm, null) + Environment.NewLine;
                        }
                    if(property.PropertyType == typeof(List<>)) // not running through the model properties
                        foreach(PropertyInfo contactproperty in contactProperties)
                        {
                            _body += contactproperty.Name + " = " + contactproperty.GetValue(cm, null) + Environment.NewLine;
                        }
                }
}

使用反射遍历嵌套在Object中的Object List

如果我理解正确的话,您想要输出公司和列表内部属性中的任何属性。

public static void SendEmail(Company cm)
{
  string _body = "";
  string _subject = "ASN Form Request";
  _body = ReflectObject(cm, _body)
}
public static string ReflectObject(object obj, string body)
{
  var type = obj.GetType();
  var properties = type.GetProperties();
  foreach(PropertyInfo property in properties)
  {
    if (property.PropertyType == typeof(string) || property.PropertyType == typeof(int) || property.PropertyType == typeof(bool))
      body += property.Name + " = " + property.GetValue(cm, null) + Environment.NewLine;
    if (property.PropertyType == typeof(List<>))
    {
      var list = property.GetValue(obj, null)
      foreach(var item in list)
      {
        ReflectObject(item, body);
      }
    }
  }
  return body;
}