Setting all null object parameters to string.empty

后端 未结 1 890
青春惊慌失措
青春惊慌失措 2021-01-25 18:37

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

相关标签:
1条回答
  • 2021-01-25 19:22

    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);
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题