/// <summary> /// 获取属性 /// </summary> /// <typeparam name="T">属性类型</typeparam> /// <param name="p">要获取的对象</param> /// <param name="key">属性名</param> /// <param name="defaultValue">默认值</param> /// <returns></returns> public static T YusProp <T>(this object p, string key, T defaultValue = default) { if (p == null) { return(defaultValue); } var type = p.GetType(); var prop = type.GetProperty(key, BindingFlags.Public | BindingFlags.Instance); if (prop == null) { return(defaultValue); } var value = prop.GetValue(key, null); if (value == null) { return(defaultValue); } try { return(value.YusToJson().YusToObject <T>()); } catch (Exception e) { YusDebug.ConsoleLog(e); return(defaultValue); } }
/// <summary> /// 获取指定键的值,并将其反序列化为对象,指定键不存在时返回默认值 /// </summary> /// <typeparam name="T">值的类型</typeparam> /// <param name="nvc">当前集合</param> /// <param name="key">要获取的键</param> /// <param name="defaultValue">默认值</param> /// <returns></returns> public static T YusGetObject <T>(this NameValueCollection nvc, string key, T defaultValue = default) { var str = nvc.YusGetString(key, null); try { return(str.YusToObject <T>()); } catch (Exception e) { YusDebug.ConsoleLog(e); return(defaultValue); } }
/// <summary> /// 获取字典中指定键的值(该值必须是要转化对象的 JSON 字符串),并将其序列化为指定对象,如果键不存在或 JSON 不正确则返回指定的默认值 /// </summary> /// <typeparam name="T">要指定的返回值类型</typeparam> /// <param name="dict">要获取值的字典</param> /// <param name="key">指定键</param> /// <param name="defaultValue">键不存在或 JSON 不正确时返回的默认值</param> /// <returns>指定键的值或者默认值</returns> public static T YusDictObject <T>(this Dictionary <string, object> dict, string key, T defaultValue = default(T)) { var str = dict.YusDictString(key, null); try { return(str.YusToObject <T>()); } catch (Exception e) { YusDebug.ConsoleLog(e); return(defaultValue); } }
/// <summary> /// 获取指定键的值,指定键不存在时返回默认值 /// </summary> /// <typeparam name="T">值的类型</typeparam> /// <param name="nvc">当前集合</param> /// <param name="key">要获取的键</param> /// <param name="defaultValue">默认值</param> /// <returns></returns> public static T YusGetValue <T>(this NameValueCollection nvc, string key, T defaultValue = default) { if (nvc == null) { return(defaultValue); } if (!nvc.AllKeys.Contains(key)) { return(defaultValue); } var value = nvc[key]; try { return(value.YusToJson().YusToObject <T>()); } catch (Exception e) { YusDebug.ConsoleLog(e); return(defaultValue); } }
/// <summary> /// 获取字典中指定键的值,并将其转化为指定类型,如果键不存在则返回指定的默认值 /// </summary> /// <typeparam name="T">要指定的返回值类型</typeparam> /// <param name="dict">要获取值的字典</param> /// <param name="key">指定键</param> /// <param name="defaultValue">键不存在时返回的默认值</param> /// <returns>指定键的值或者默认值</returns> public static T YusDictValue <T>(this Dictionary <string, object> dict, string key, T defaultValue = default(T)) { if (dict == null) { return(defaultValue); } if (!dict.ContainsKey(key)) { return(defaultValue); } var value = dict[key]; try { return(value.YusToJson().YusToObject <T>()); } catch (Exception e) { YusDebug.ConsoleLog(e); return(defaultValue); } }