我正在尝试编写一些代码来迭代我的业务对象并将它们的内容转储到日志文件中。
为此,我希望能够找到所有公共属性并使用反射输出它们的名称和值——我还希望能够检测集合属性并对其进行迭代。
假设有两个这样的类:
public class Person
{
private List<Address> _addresses = new List<Address>();
public string Firstname { get; set; }
public string Lastname { get; set; }
public List<Address> Addresses
{
get { return _addresses; }
}
}
public class Address
{
public string Street { get; set; }
public string ZipCode { get; set; }
public string City { get; set; }
}
我目前有类似这样的代码,可以找到所有公共属性:
public void Process(object businessObject)
{
// fetch info about all public properties
List<PropertyInfo> propInfoList = new List<PropertyInfo>(businessObject.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public));
foreach (PropertyInfo info in propInfoList)
{
// how can I detect here that "Addresses" is a collection of "Address" items
// and then iterate over those values as a "list of subentities" here?
Console.WriteLine("Name '{0}'; Value '{1}'", info.Name, info.GetValue(businessObject, null));
}
}
但我无法弄清楚如何检测给定属性(例如类Addresses
上的Person
)是对象的集合Address
?似乎找不到propInfo.PropertyType.IsCollectionType
房产(或类似的东西会给我我正在寻找的信息)
我(不成功)尝试过类似的事情:
info.PropertyType.IsSubclassOf(typeof(IEnumerable))
info.PropertyType.IsSubclassOf(typeof(System.Collections.Generic.List<>))
info.PropertyType.IsAssignableFrom(typeof(IEnumerable))