加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在一个对象中表示n个对象

发布时间:2020-12-15 23:29:35 所属栏目:百科 来源:网络整理
导读:在一个sql语句中,join的结果返回多个建模对象,我想到了一种模型化的方法并提出了 class JoinObjectsMapper { //add 2 fields one for the PK value and one for the name of the PK internal readonly DictionaryType,object Objs; public JoinObjectsMapper
在一个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>();

仍然得到正确的类型,避免铸造?

解决方法

如果您不喜欢必须执行JoinObjectsMapper的强制转换,则可以将强制转换添加到JoinObjectsMapper定义:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读