qq_41712950
2022-06-01 18:46
采纳率: 60%
浏览 19

C#中实例化类、动态分配内存的问题

问题遇到的现象和发生背景

ddxx和ddmx是我定义的两个实体类,xx是一个实例,我想改动xx的一些值,但是基本值不变,生成不一样的实例,然后放进List集合里,但是循环后发现打印集合出来的是同一个内容。。
想请教:
1、这个问题是怎么产生的?应该是与指针、动态分配有关?
2、应该怎么写?

问题相关代码,请勿粘贴截图
            var xx = new ddxx
            {
                CPDL = dataRow.Cells["产品大类"].Value.ToString(),

                XZ = dataRow.Cells["性质"].Value.ToString(),
                DDXZ = dataRow.Cells["订单性质"].Value.ToString()
            };
            var mx = new ddmx
            {
                DDBM = dataRow.Cells["订单编码"].Value.ToString(),
                sl = Convert.ToInt32(dataRow.Cells["数量"].Value.ToString()),
                XSSL = Convert.ToInt32(dataRow.Cells["数量"].Value.ToString()),
                WLH = dataRow.Cells["物料号"].Value.ToString(),
                NAME = dataRow.Cells["物料名称"].Value.ToString(),
                JHKGRQ = dataRow.Cells["计划完工日期"].Value.ToString(),
                JHWGRQ = dataRow.Cells["计划完工日期"].Value.ToString(),
                MCDDBM = dataRow.Cells["订单编码"].ToString()
            };
            #endregion
            var node = getParentNode(dataTable, dataRow.Cells["物料号"].Value.ToString());
            getNode(dataTable, node);
            Console.WriteLine("制造件个数:"+_nodes.Count.ToString());
            foreach (Node n in _nodes)//个数为3
            {
                //修改节点信息
                TpublicClass.ConnectionString_MESDB = _ConnectionString;
                string id ="1";
                //string id = TpublicClass.GetAutoNum("DDH", "订单编号DDH");
                string name = getwlname(n.Code);
                xx.DDH = Convert.ToInt32(id);
                xx.CPMC = name;
                mx.DDBM = "MO" + id.PadLeft(8, '0');
                mx.DDH = id;
                mx.NAME = name;
                mx.WLH = n.Code;
                Console.WriteLine("mx:" + JsonConvert.SerializeObject(mx));
                Console.WriteLine("xx:" + JsonConvert.SerializeObject(xx));
                /*                    mx.JHWGRQ = Convert.ToDateTime(mx.JHWGRQ).AddDays(-1 * n.Date).ToString();
                                    mx.JHKGRQ = Convert.ToDateTime(mx.JHWGRQ).AddDays(-5).ToString();*/
                _ddxxList.Add(xx);
                _ddmxList.Add(mx);
            } 
运行结果及报错内容

订单:{"DDH":"1","XMH":1,"DDBM":"MO00000001","sl":0,"ZT":"01","XSSL":0,"JHZT":"01","WLH":"11GW0301000002","MXBOM":"完整BOM","NAME":"主控半成品01"}
订单:{"DDH":"1","XMH":1,"DDBM":"MO00000001","sl":0,"ZT":"01","XSSL":0,"JHZT":"01","WLH":"11GW0301000002","MXBOM":"完整BOM","NAME":"主控半成品01"}
订单:{"DDH":"1","XMH":1,"DDBM":"MO00000001","sl":0,"ZT":"01","XSSL":0,"JHZT":"01","WLH":"11GW0301000002","MXBOM":"完整BOM","NAME":"主控半成品01"}
**
前面两句分别打印xx和mx,值都是正常的,但是循环打印list中的xx和mx,值就是相同的了**

我的解答思路和尝试过的方法
我想要达到的结果

3条回答 默认 最新

相关推荐 更多相似问题