【问题标题】:Setting all null object parameters to string.empty将所有空对象参数设置为 string.empty
【发布时间】:2017-05-24 10:36:46
【问题描述】:

我有一个包含字符串的对象和包含字符串的其他对象,我需要做的是确保该对象和任何子对象都有一个空字符串而不是空值,到目前为止这工作正常:

foreach (PropertyInfo prop in contact.GetType().GetProperties())
{
    if(prop.GetValue(contact, null) == null)
    {
        prop.SetValue(contact, string.empty);
    }
}

问题是这只适用于对象字符串而不是子对象字符串。如果发现是null,有没有办法也循环所有子对象并将它们的字符串设置为string.Empty

以下是“联系人”对象的示例:

new contact 
{
  a = "",
  b = "",
  c = ""
  new contact_sub1 
  {
     1 = "",
     2 = "",
     3 = ""
  },
  d = ""
}

基本上我还需要检查contact_sub1 是否有空值并将值替换为空的string

【问题讨论】:

  • 方法相同但递归
  • 也使用递归来处理“子对象”。

标签: c# propertyinfo


【解决方案1】:

您可以修改当前代码以获取所有子对象,然后对空字符串属性执行相同的检查。

public void SetNullPropertiesToEmptyString(object root) {
    var queue = new Queue<object>();
    queue.Enqueue(root);
    while (queue.Count > 0) {
        var current = queue.Dequeue();
        foreach (var property in current.GetType().GetProperties()) {
            var propertyType = property.PropertyType;
            var value = property.GetValue(current, null);
            if (propertyType == typeof(string) && value == null) {
                property.SetValue(current, string.Empty);
            } else if (propertyType.IsClass && value != null && value != current && !queue.Contains(value)) {
                queue.Enqueue(value);
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-06
    • 1970-01-01
    • 1970-01-01
    • 2020-03-23
    • 1970-01-01
    相关资源
    最近更新 更多