c# - 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
}
}
}
解决方案
这应该对您有用,只需使用GetValue
方法并将值转换为IList
,然后检查是否为空并通过设置此值SetValue
to 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);
}
}
}
}
推荐阅读
- ios - 在ios swift中使用AVPlayer播放mpga格式文件
- git - 无需快进即可获得更改
- javascript - clearInterval() 函数不起作用,无法弄清楚为什么..?
- javascript - 使用 React-Native / JavaScript 在服务器和客户端之间同步时钟
- python - 将 python 列表插入 SQLite 单元格
- apache-spark - 为什么 getKerberosTransport 需要 3 部分 kerborse 原则?
- spring - Spring Security SAML 与 samesite=Lax 的兼容性
- php - Woo-commerce - 添加到购物车循环 - 如何将 html 添加到按钮
- spring - Spring Bean 覆盖我的 ObjectMapper 配置
- php - 连接两个表并在laravel中获取行