今天写了一个数据库的帮助类,代码如下。
public static class DbEx
{
public static dynamic ReadToObject(this IDataReader reader)
{
var obj = new DbObject(); for (int i = ; i < reader.FieldCount; i++)
{
obj[reader.GetName(i)] = new DbField()
{
DbData = reader[i]
};
} return obj;
} public class DbObject : DynamicObject
{
//自己实现一个,不用ExpandoObject, 以支持无视大小写读取
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = this[binder.Name];
return true;
} Dictionary<string, object> _values = new Dictionary<string, object>(StringComparer.CurrentCultureIgnoreCase); public object this[string index]
{
get => _values[index];
set => _values[index] = value;
}
} public class DbField
{
public object DbData { get; set; } public T Value<T>()
{
return (T)Convert.ChangeType(DbData, typeof(T));
} public static implicit operator string(DbField data) => data.Value<string>();
public static implicit operator int(DbField data) => data.Value<int>();
public static implicit operator DateTime(DbField data) => data.Value<DateTime>();
public static implicit operator double(DbField data) => data.Value<double>();
public static implicit operator bool(DbField data) => data.Value<bool>();
}
}
简单的来讲,可以把如下代码
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型,会进行自动类型转换
- 自动识别目标类型,不需要显示强制类型转换,更加简洁