private void SetDefaultValues(object obj) { // 获取对象的类型 Type type = obj.GetType(); // 获取所有属性 PropertyInfo[] properties = type.GetProperties(); foreach (PropertyInfo property in properties) { // 检查属性是否为字符串类型 if (property.PropertyType == typeof(string)) { // 获取属性值 object value = property.GetValue(obj); // 如果属性值为null或空字符串,则设置默认值 if (value == null) { property.SetValue(obj, string.Empty); } } // 这里可以给其他类型赋值 } }
给对象所有的属性赋默认值 这里举例string类型
于 2024-12-12 10:50:56 首次发布