Setting all null object parameters to string.empty

最后都变了- 提交于 2019-12-02 03:57:49

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);
            }
        }
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!