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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-11 05:54