对象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 = ConvertToPropType(property, dictionary.Values.ElementAt<string>(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 == null || Convert.IsDBNull(value)) ? null : Convert.ChangeType(value, propType, null);
            }
            return cstVal;
        }

上一篇:Linux服务器安全配置


下一篇:剑指Offer 用两个栈实现队列