问题
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
.
回答1:
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);
}
}
}
}
来源:https://stackoverflow.com/questions/44155924/setting-all-null-object-parameters-to-string-empty