为类型的属性设置非空的默认值

最近在做数据库开发时,向数据库保存数据,经常出现字段为空无法保存的问题。于是想到是否可以通过反射为实体类中那些为null的字段设置默认值。这样就可以避免保存数据时需要对每一个地段进行判空操作。下面的SetDefaultToProperties方法就是来完成这个操作的。T为与数据库表对应的实体类,遍历T中每一个属性并设置默认值,对于string要特殊处理,因为系统并未将string看成值类型,会返回null,所以自己将string类型处理成空串。

        public void SetDefaultToProperties(T obj)
        {
            Type type = typeof(T);
            PropertyInfo[] props = type.GetProperties();
            foreach (PropertyInfo property in props)
            {
                if (property.CanWrite)
                {
                    Type propertyType = property.PropertyType;
                    if (propertyType.Name == "String")
                    {
                        property.SetValue(obj, string.Empty, null);
                    }
                    else
                    {
                        object value = GetDefaultForType(propertyType);
                        property.SetValue(obj, value, null);
                    }
                }
            }
        }

GetDefaultForType方法通过反射获取类型的默认值。

        public static object GetDefaultForType(Type type)
        {
            return type.IsValueType ? Activator.CreateInstance(type) : null;
        }

你可能感兴趣的:(C#)