今天写了一个数据库的帮助类,代码如下。
1 public static class DbEx 2 { 3 public static dynamic ReadToObject(this IDataReader reader) 4 { 5 var obj = new DbObject(); 6 7 for (int i = 0; i < reader.FieldCount; i++) 8 { 9 obj[reader.GetName(i)] = new DbField() 10 { 11 DbData = reader[i] 12 }; 13 } 14 15 return obj; 16 } 17 18 public class DbObject : DynamicObject 19 { 20 //自己实现一个,不用ExpandoObject, 以支持无视大小写读取 21 public override bool TryGetMember(GetMemberBinder binder, out object result) 22 { 23 result = this[binder.Name]; 24 return true; 25 } 26 27 Dictionary<string, object> _values = new Dictionary<string, object>(StringComparer.CurrentCultureIgnoreCase); 28 29 public object this[string index] 30 { 31 get => _values[index]; 32 set => _values[index] = value; 33 } 34 } 35 36 public class DbField 37 { 38 public object DbData { get; set; } 39 40 public T Value<T>() 41 { 42 return (T)Convert.ChangeType(DbData, typeof(T)); 43 } 44 45 public static implicit operator string(DbField data) => data.Value<string>(); 46 public static implicit operator int(DbField data) => data.Value<int>(); 47 public static implicit operator DateTime(DbField data) => data.Value<DateTime>(); 48 public static implicit operator double(DbField data) => data.Value<double>(); 49 public static implicit operator bool(DbField data) => data.Value<bool>(); 50 } 51 }
简单的来讲,可以把如下代码
GpsData parse(IDataReader reader)
{
return
new
GpsData()
{
IsValid = (bool)reader["IsValid"],
Location = new
Location ()
{
Lon = (double)reader["Lon"],
Lat = (double)reader["Lat"],
},
Angle = (double)reader["Angle"],
Speed = (double)reader["Speed"]),
UpdateTime = (double)reader["Speed"]),
};
}
转换为如下形式
GpsData
parse(IDataReader reader)
{
var obj = reader.ReadToObject();
var state = new
GpsData()
{
IsValid = obj.IsValid,
Location = new
Location()
{
Lon = obj.Lon,
Lat = obj.Lat,
},
Angle = obj.Angle,
Speed = obj.Speed,
UpdateTime = obj.UpdateTime,
};
return state;
}
主要还是利用dynamic的特性,转换成这样的好处有:
-
以属性的方式替换下标方式读取,更加间接直观
-
属性的方式读取变量时不分大小写
-
支持自动类型转换,例如,如果数据库里的类型是int型,而目标是string型,会进行自动类型转换
-
自动识别目标类型,不需要显示强制类型转换,更加简洁