C#如何将对象内所有空列表转换为null

3
首先,我知道流行的建议是避免完全返回空列表。但由于各种原因,现在我别无选择,只能这样做。
我的问题是如何通过对象的属性(可能是通过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
        }
    }
}

你能提供一些数据样本和期望的结果吗? - Saif
1
这篇文章 https://dev59.com/YXNA5IYBdhLWcg3wPLL- 展示了如何检查列表类型...然后通过dynamic或反射调用.Count属性不应该是一个问题... - Alexei Levenkov
1
你链接的答案中说“当返回集合或可枚举对象时,永远不要返回null。总是返回一个空的可枚举对象/集合……”;你是怎么理解成“避免返回空列表”的呢? - Dour High Arch
@DourHighArch 谈论婉辞... - fhcimolin
1个回答

5

这个方法适用于您,只需使用 GetValue 方法并将值转换为 IList ,然后检查是否为空,并通过 SetValue 将此值设置为 null

private static void IfEmptyListThenNull<T>(T myObject)
        {
            foreach (PropertyInfo propertyInfo in myObject.GetType().GetProperties())
            {
                if (propertyInfo.PropertyType.IsGenericType && propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(List<>))
                {
                    if (((IList)propertyInfo.GetValue(myObject, null)).Count == 0)
                    {
                        propertyInfo.SetValue(myObject, null);
                    }
                }
            }
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接