C# 如何将对象内的所有空列表变成 null

fhc*_*lin 3 c# reflection null list

首先,我知道流行的建议是您应该完全避免返回空列表。但到目前为止,由于种种原因,我别无选择,只能这样做。

我要问的是如何迭代对象的属性(可能通过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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

chi*_*s0v 5

这应该适合您,只需使用GetValue方法并将值转换为IList,然后检查是否为空并通过SetValueto设置该值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);
                    }
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)