首页 > 解决方案 > C#如何将对象内的所有空列表变为null

问题描述

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

我要问的是如何遍历对象的属性(可能通过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
        }
    }
}

标签: c#listreflectionnull

解决方案


这应该对您有用,只需使用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);
                    }
                }
            }
        }

推荐阅读