将所有空对象参数设置为string.empty [英] Setting all null object parameters to string.empty

查看:81
本文介绍了将所有空对象参数设置为string.empty的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an object that is contains strings and further objects that contain strings, what i need to do is ensure that the object and any sub objects have an empty string and not a null value, so far this works fine:

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

问题是这仅适用于对象字符串,而不适用于子对象字符串.有没有办法遍历所有子对象并将它们的字符串设置为string.Empty(如果发现是null)?

the problem is this only works for the objects strings and not the sub-objects strings. Is there a way to also loop over all sub-objects and set their strings to string.Empty if found to be null?

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

Here's an example of the 'contact' object:

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

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

Basically I also need to check in contact_sub1 for nulls and replace the value with an empty string.

推荐答案

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

You can modify your current code to get all sub objects and then perform the same check for null string properties.

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);
            }
        }
    }
}

这篇关于将所有空对象参数设置为string.empty的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆