/// <summary> /// 读取本地AppSettings中的值 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static T AppSettings <T>(string key, T defaultValue = default(T)) { string value = ConfigurationManager.AppSettings[key]; if (value == null) { return(defaultValue); } DefalutDataConverter converter = new DefalutDataConverter(); return((T)converter.Parse(typeof(T), value)); }
public static T Get <T>(this IDictionary <string, string> dic, string key, T defaultValue = default(T)) { if (dic == null) { return(defaultValue); } if (!dic.ContainsKey(key)) { return(defaultValue); } DefalutDataConverter converter = new DefalutDataConverter(); return((T)converter.Parse(typeof(T), dic[key])); }
public object Parse(Type type, string value) { if (string.IsNullOrEmpty(value)) { return(null); } if (!value.Contains("=")) { throw new Exception("格式错误,正确格式形如:" + "Key1=Value1" + Environment.NewLine + "Key2=Value2"); } value = value.Replace("\r\n", "\n"); string[] items = value.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); if (type == typeof(IDictionary <string, string>)) { IDictionary <string, string> dic = new Dictionary <string, string>(StringComparer.CurrentCultureIgnoreCase); foreach (string item in items) { if (!value.Contains("=")) { continue; } string[] keyValuePairs = item.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries); if (keyValuePairs.Length != 2) { continue; } string strKey = keyValuePairs[0].Trim(); string strValue = keyValuePairs[1].Trim(); dic.Add(strKey, strValue); } return(dic); } else { object obj = Activator.CreateInstance(type, true); foreach (string item in items) { if (!value.Contains("=")) { continue; } string[] keyValuePairs = item.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries); if (keyValuePairs.Length != 2) { continue; } string strKey = keyValuePairs[0].Trim(); string strValue = keyValuePairs[1].Trim(); PropertyInfo propertyInfo = type.GetProperties().FirstOrDefault(m => m != null && string.Compare(m.GetAlias(), strKey, StringComparison.OrdinalIgnoreCase) == 0); if (propertyInfo == null) { continue; } DefalutDataConverter converter = new DefalutDataConverter(); object itemValue = converter.Parse(propertyInfo.PropertyType, strValue); propertyInfo.SetValue(obj, itemValue, null); } return(obj); } }