在一个对象中表示n个对象

时间:2015-12-23 02:51:51

标签: c# generics dictionary

在一个sql语句中,join的结果返回多个建模对象,我想到了一种建模方法,并想出了

 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>();

仍然可以获得正确的类型并避免投射?

2 个答案:

答案 0 :(得分:4)

如果您不想执行JoinObjectsMapper的强制转换,可以将强制转换添加到JoinObjectsMapper定义中:

public T Ref<T>(){
    return (T)Objs[typeof(T)];
}

答案 1 :(得分:3)

要注意捕捉异常的另一件事。

public T Ref<T>(){
    if (!(Objs[typeof(T)] is T)
        throw new InvalidCastException();

    return (T)Objs[typeof(T)];
}