NET 反射,对可空类型动态赋值
1.代码如下:
var type = typeof(CodeBuilderVo); var itemDbModel = new CodeBuilderVo(); var properArr = type.GetPublicProperties(); foreach (var itemProper in properArr) { var itemName = itemProper.Name; object itemValue = "1024"; var itemType = itemProper.PropertyType; var itemTypeName = itemType.Name; // 支持可空类型转换 itemValue = itemTypeName.Contains("Nullable") ? Convert.ChangeType(itemValue, Nullable.GetUnderlyingType(itemType)) : Convert.ChangeType(itemValue, itemType); type.GetProperty(itemName).SetValue(itemDbModel, itemValue); }