【发布时间】:2019-03-07 17:38:24
【问题描述】:
首先,我知道您应该avoid returning empty lists 的流行建议。但到目前为止,由于种种原因,我别无选择,只能这样做。
我要问的是如何迭代对象的属性(可能通过Reflection),获取我可能找到的任何列表并检查它是否为空。如果是,则将其转为null,否则,保留它。
我坚持使用以下代码,其中包括对Reflection 的一些尝试:
private static void IfEmptyListThenNull<T>(T myObject)
{
foreach (PropertyInfo propertyInfo in myObject.GetType().GetProperties())
{
if (propertyInfo.PropertyType.IsGenericType && propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(List<>))
{
//How to know if the list i'm checking is empty, and set its value to null
}
}
}
【问题讨论】:
-
能否提供数据样本和预期结果。
-
stackoverflow.com/questions/1043755/… 展示了如何检查列表...然后通过
dynamic或反射调用.Count属性应该不是问题... -
您链接到的答案是“在返回集合或可枚举时永远不要返回 null。总是返回一个空的可枚举/集合……”;您如何将其解释为“避免返回空列表”?
-
@DourHighArch 谈委婉语...
标签: c# list reflection null