using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace GpsCardGatewayPosition.Model.Context { public abstract class ContextBase { /// /// 反序列化 将 属性名:属性值 AND 属性名=属性值 字符串反序列化为对象 /// /// public void Deserlize(string val) { if (string.IsNullOrEmpty(val)) return; var items = val.Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries); foreach (var item in items) { var kv = item.Split('='); if (kv.Length == 2) SetValue(this, kv[0], kv[1]); } } /// /// 重写 ToString 方法,将所有属性拼接成 属性名=属性值 AND 属性名=属性值 格式的字符串 /// /// public override string ToString() { var tStr = string.Empty; var properties = GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); foreach (var item in properties) { var name = item.Name; var value = item.GetValue(this, null); if (value != null) { if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String")) { // Skipped insecurity tStr += string.Format("{0}={1}&", name, value); } } } return tStr.TrimEnd('&').ToLower(); } /// /// 类型匹配 /// /// /// /// public static bool IsType(Type type, string typeName) { if (type.ToString() == typeName) return true; return type.ToString() != "System.Object" && IsType(type.BaseType, typeName); } /// /// 给类的属性设置值 /// /// /// /// public static void SetValue(object entity, string fieldName, string fieldValue) { var entityType = entity.GetType(); var propertyInfo = entityType.GetProperty(fieldName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); if (propertyInfo == null) return; if (IsType(propertyInfo.PropertyType, "System.String")) { propertyInfo.SetValue(entity, fieldValue, null); } if (IsType(propertyInfo.PropertyType, "System.Boolean")) { propertyInfo.SetValue(entity, Boolean.Parse(fieldValue), null); } if (IsType(propertyInfo.PropertyType, "System.Nullable`1[System.Boolean]")) { propertyInfo.SetValue(entity, fieldValue != "" && Boolean.Parse(fieldValue), null); } if (IsType(propertyInfo.PropertyType, "System.Int32")) { propertyInfo.SetValue(entity, fieldValue != "" ? int.Parse(fieldValue) : 0, null); } if (IsType(propertyInfo.PropertyType, "System.Nullable`1[System.Int32]")) { propertyInfo.SetValue(entity, fieldValue != "" ? int.Parse(fieldValue) : 0, null); } if (IsType(propertyInfo.PropertyType, "System.Decimal")) { try { propertyInfo.SetValue(entity, fieldValue != "" ? Decimal.Parse(fieldValue) : new Decimal(0), null); } catch (Exception) { propertyInfo.SetValue(entity, new Decimal(0), null); } } if (IsType(propertyInfo.PropertyType, "System.Nullable`1[System.DateTime]")) { if (fieldValue != "") { try { propertyInfo.SetValue( entity, (DateTime?)DateTime.ParseExact(fieldValue, "yyyy-MM-dd HH:mm:ss", null), null); } catch { propertyInfo.SetValue(entity, (DateTime?)DateTime.ParseExact(fieldValue, "yyyy-MM-dd", null), null); } } else propertyInfo.SetValue(entity, null, null); } } } }