【问题标题】:Representing an n number of objects in one object在一个对象中表示 n 个对象
【发布时间】:2015-12-23 02:51:50
【问题描述】:

在一条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>();

仍然获得正确的类型并避免强制转换?

【问题讨论】:

  • 你不能。为避免强制转换,您需要在编译时知道对象的类型。
  • 您不喜欢演员表的运行时影响,还是不得不写出来?
  • @James 不得不写出来

标签: c# generics dictionary


【解决方案1】:

如果您只是不喜欢在 JoinObjectsMapper 外部执行转换,您可以将转换添加到 JoinObjectsMapper 定义中:

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

【讨论】:

    【解决方案2】:

    捕捉异常的另一件事。

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

    【讨论】:

    • 我认为不可能有一个键的值不是键的类型。字典仅附加到使用 Objs[o.GetType()] = o;
    • @BenKnoble 为什么抛出无效的强制转换异常?如果对象无法转换为该类型,则转换无论如何都会抛出该异常。这就像说return numerator == 0 ? 0 : numerator / denominator;
    猜你喜欢
    • 2016-07-07
    • 2012-07-30
    • 1970-01-01
    • 2015-11-12
    • 2020-11-28
    • 1970-01-01
    • 2018-07-08
    • 1970-01-01
    • 2021-07-11
    相关资源
    最近更新 更多