表示一个对象中的n个对象
本文关键字:对象 一个对象 表示 | 更新日期: 2023-09-27 18:27:57
在sql语句中,联接的结果返回多个建模对象,我想了一种方法来建模它们,并提出了
class JoinObjectsMapper
{
//add 2 fields one for the PK value and one for the name of the PK
internal readonly Dictionary<Type, object> Objs;
public JoinObjectsMapper(params object[] objs)
{
Objs = new Dictionary<Type, object>();
foreach(var o in objs)
{
Objs[o.GetType()] = o;
}
}
public object this[Type key]
{
get { return Objs[key]; }
set { Objs[key] = key; }
}
}
示例用法:
var custmer = new Customer { customer_id = 1, customer_name = "zxc" };
var order = new Order { order_id = 1, customer_id = 1, order_amount = 200.30m };
var mapper = new JoinObjectsMapper(custmer, order);
var cus = mapper[typeof(Customer)] as Customer;
var order = mapper[typeof(Order)] as Order;
这是有效的,只是我不喜欢在检索对象后必须强制转换它,如果我使用泛型,那么它对n个对象都不起作用,除非我写了这么多据我所知的重载。
知道如何将我的对象作为检索吗
var cus = mapper[typeof(Customer)];
var order = mapper[typeof(Order)];
或
var cus = mapper.Ref<Customer>();
var order = mapper.Ref<Order>();
仍然选择正确的类型并避免铸造?
如果您不喜欢在JoinObjectsMapper外部执行强制转换,您可以将强制转换添加到JoinObjectsMaper定义中:
public T Ref<T>(){
return (T)Objs[typeof(T)];
}
捕获异常需要注意的另一件事。
public T Ref<T>(){
if (!(Objs[typeof(T)] is T)
throw new InvalidCastException();
return (T)Objs[typeof(T)];
}