Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

c# - Setting all null object parameters to 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);
    }
}

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 = ""
}

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...