我需要一种方法来循环遍历每个对象的属性并记录属性名称和值。然而,有时,我点击了一个列表对象的属性,整个事情就崩溃了。我从各种 SO 帖子中收集了以下条件,但每次都返回 false。想知道如何测试您的方法属性是否是通用集合类型?
类定义
public class DtccProducer
{
public string ProducerDateOfBirth { get; set; }
public string ProducerGender { get; set; }
public string TransactionType { get; set; }
public List<BigAddress> Addresses { get; set; }
public List<BigCommunicationItem> Communications { get; set; }
}
方法
private static void ParseProducer(object obj)
{
StringBuilder s = new StringBuilder();
Type objType = obj.GetType();
foreach (PropertyInfo info in objType.GetProperties())
{
string key = info.Name;
Type propType = info.PropertyType;
if (propType.IsGenericType && typeof(ICollection<>).IsAssignableFrom(propType.GetGenericTypeDefinition()))
{
// This condition never passes - always evaluates to false
}
else
{
string value = (string) info.GetValue(obj, null);
_sb.AppendLine(key + ": " + value);
}
}
}
最佳答案
这是我用来识别日志中列表的代码:
if (!propType.IsPrimitive && !propType.IsEnum && propType != typeof(string) && propType.GetInterfaces().Any(x => x.IsGenericType
&& x.GetGenericTypeDefinition() == typeof(IEnumerable<>)))
编辑:我添加了一些额外的检查来过滤原始类型(int、bool 等)、枚举和字符串。
关于c# - 确定匿名类型的属性是否为泛型集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31819164/