将所有null对象参数设置为string.empty

时间:2017-05-24 10:36:47

标签: c# propertyinfo

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

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

问题是这只适用于对象字符串而不适用于子对象字符串。是否有办法循环遍历所有子对象,如果发现string.Empty,则将其字符串设置为null

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

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

基本上我还需要在contact_sub1中检查空值,并将值替换为空string

1 个答案:

答案 0 :(得分: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);
            }
        }
    }
}