private Dictionary <string, object> RenderDictioary(ServiceReader reader, Dictionary <string, ParameterInfo> parameters) { Dictionary <string, object> dictionarys = new Dictionary <string, object>(); foreach (string key in reader.Values.AllKeys) { if (parameters.ContainsKey(key)) { var reqValue = reader.Values[key]; Type parameterType = parameters[key].ParameterType; object parameterValue = null; if (string.IsNullOrWhiteSpace(reqValue)) { parameterType = TypeConvertHelper.GetUnderlyingType(parameterType); parameterValue = TypeConvertHelper.ChangeType(parameterType, reqValue); continue; } if (TypeConvertHelper.IsPrimitive(parameterType)) { parameterType = TypeConvertHelper.GetUnderlyingType(parameterType); parameterValue = TypeConvertHelper.ChangeType(parameterType, reqValue); dictionarys.Add(key, parameterValue); } else if (parameterType.IsClass) { parameterValue = JsonConvertHelper.DeserializeObject(reqValue, parameterType); dictionarys.Add(key, parameterValue); } } } return(dictionarys); }
/// <summary> /// 设定对象某个属性的值 /// </summary> /// <param name="obj"></param> /// <param name="propertyName"></param> /// <param name="proValue"></param> /// <param name="ignoreError">是否忽略错误消息</param> public static void SetProperty(object obj, string propertyName, object proValue, bool ignoreError) { Type type = obj.GetType(); PropertyInfo property = type.GetProperty(propertyName); if (!((property != null) && property.CanWrite)) { if (!ignoreError) { throw new Exception(string.Format("The setter of property named '{0}' not found in '{1}'.", propertyName, type)); } } else { try { proValue = TypeConvertHelper.ChangeType(property.PropertyType, proValue); } catch { } object[] args = new object[] { proValue }; type.InvokeMember(propertyName, BindingFlags.SetProperty | BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase, null, obj, args); } }
/// <summary> /// 返回可空类型的基础类型,非空类型返回本身 /// </summary> /// <param name="type"></param> /// <returns></returns> public static Type GetUnderlyingType(Type type) { if (!TypeConvertHelper.IsNullableType(type)) { return(type); } return(Nullable.GetUnderlyingType(type)); }
/// <summary> /// Type 是否为基元类型之一 /// </summary> /// <param name="t"></param> /// <returns></returns> public static bool IsPrimitive(Type t) { if (t.IsGenericType) { return(TypeConvertHelper.IsNullableType(t) && TypeConvertHelper.IsPrimitive(Nullable.GetUnderlyingType(t))); } return(t == typeof(string) || t == typeof(short) || t == typeof(ushort) || t == typeof(int) || t == typeof(uint) || t == typeof(long) || t == typeof(ulong) || t == typeof(float) || t == typeof(double) || t == typeof(decimal) || t == typeof(char) || t == typeof(byte) || t == typeof(bool) || t == typeof(DateTime) || t == typeof(Guid)); }
/// <summary> /// 是否是值类型或空值类型 /// </summary> /// <param name="type"></param> /// <returns></returns> public static bool AllowsNullValue(Type type) { return(!type.IsValueType || TypeConvertHelper.IsNullableType(type)); }