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;
}