【问题标题】:C# How to turn all empty lists inside object into nullC#如何将对象内的所有空列表变为null
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-25
    • 1970-01-01
    • 1970-01-01
    • 2019-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多