简体   繁体   English

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

[英]C# How to turn all empty lists inside object into null

First of all, i'm aware of the popular advice that you should avoid returning empty lists at all. 首先,我知道你应该避免返回空列表的流行建议。 But as of now, due to a myriad of reasons, i'm met with no other choice but to do just that. 但截至目前,由于种种原因,我除了做到这一点外别无选择。

What i'm asking is how do I iterate through the properties of an object (probably through Reflection ), take whatever lists I may find and check if it's empty. 我要问的是如何迭代对象的属性(可能通过Reflection ),取出我可能找到的任何列表并检查它是否为空。 If so, then turn it into null , otherwise, leave it be. 如果是这样,那么把它变成null ,否则,保持原样。

I'm stuck with the following code, which includes somewhat of a try with Reflection : 我坚持使用以下代码,其中包含一些使用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
        }
    }
}

This should work for you, just use GetValue method and cast value to IList , then check for emptiness and set this value via SetValue to null . 这应该适合你,只需使用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);
                    }
                }
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM