首页 > 代码库 > 对象Transform,对属性赋值

对象Transform,对属性赋值

private void ContructRequest(Dictionary<string, string> dictionary, CustomerSearchRequest request)
        {
            for (int i = 0; i < dictionary.Count; i++)
            {
                var property = request.GetType().GetProperties().FirstOrDefault(p => p.Name == dictionary.Keys.ElementAt<string>(i));
                if (property == null) continue;
                var propertyValue = http://www.mamicode.com/ConvertToPropType(property, dictionary.Values.ElementAt(i));
                property.SetValue(request, propertyValue, null);
            }
        }

 

对可空类型做处理:

 

public static object ConvertToPropType(PropertyInfo property, object value)
        {
            object cstVal = null;
            if (property != null)
            {
                Type propType = Nullable.GetUnderlyingType(property.PropertyType);
                bool isNullable = (propType != null);
                if (!isNullable) { propType = property.PropertyType; }
                bool canAttrib = (value != null || isNullable);
                if (!canAttrib) { throw new Exception("Cant attrib null on non nullable. "); }
                cstVal = (value =http://www.mamicode.com/= null || Convert.IsDBNull(value)) ? null : Convert.ChangeType(value, propType, null);
            }
            return cstVal;
        }