[英]Iterate through Object List nested within Object using Reflection
我正在尝试使用反射基于表单输入生成电子邮件,以更快,更理想的方式制作电子邮件。
遍历Company对象中的嵌套列表,因此_body
是Company中所有属性的长输出列表,并且是嵌套对象列表( Asn
和Contact
)。
当该方法接受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;
}
}
}
如果我理解正确,那么您希望输出公司以及列表内部属性中的所有属性。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.