

C#高阶与初心:(一)List.Add添加的到底是什么?
source link: https://www.cnblogs.com/ceachy/p/WhatDoesListAdd.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

C#高阶与初心:(一)List.Add添加的到底是什么?
前几日与同事讨论一个相对复杂的场景,需要先将中间过程存储在List中,稍后再用。同时程序类的许多线程共用了一个全局变量。
具体来说就是如下代码
。。。 _order = order1; _list.Add(_order); 。。。 _order = order2; _list.Add(_order); 。。。 _order = order3; _list.Add(_order); 。。。 _list.ForEach(o => PrintContent(o)); 。。。
对于打印内容,到底是1、2、3不同内容呢,还是都是3的内容?大家意见不一。运行一下看看结果,当然是最简单的事情,这也不是最重要的。重要的是,玩儿C#这么多年,对于这么个简单的问题,我们都有自己的见解。
一边认为,既然都是将_order添加进去,而_order又在不断变化,最后肯定是都是一样的内容。另一边认为,记录的应该是内存的实际指向,除非记录的位置明确被更改,否则不应该变化,不会随之中间变量的变化而变化。事实证明,后者是正确的。
发散一下,如果是结构体(虽然现在已经用的很少了)的话,情况又有不同。。。如果在list添加进去一个结构体,然后对传入的中间变量进行更改,并不会反映的list对应的项上。
其实回头想想,这不就是我们初学面向对象语言时经常遇到的,对于一个函数形参的指针传递与值传递问题吗?
Recommend
-
10
C#高阶与初心:(二)P/Invoke平台调用 最近某个项目要采集交易终端的信息用于监管,主要厂商给出了API,C++版的。。。开启hard模式...
-
9
How do I add users to an Announcement List? Adding users Navigate to the Announcement Lists page....
-
8
Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The f...
-
5
How do you add a dropdown list to Excel? If you want to add a dropdown to an Excel sheet with a list of values for a user to choose from, then you are in luck because it’s a fairly easy process. Example of adding a dropdown...
-
7
Drive Your Plow Over the Bones of the Dead (2009) Written by Olga Tokarczuk and translated by Antonia Lloyd-Jones Following her 2018 International Booker Prize win, Olga Tokarczuk ran the risk of being labelled...
-
10
Add 4740180 to the list of silly magic numbers Oh dear. The software fungus where bits of code take the literal characters "HTTP" as a number has expanded. Now it has a...
-
10
什么是高阶运营?高阶运营的核心能力是什么?...
-
4
add_action() WordPress函数(添加动作) do_action( string $hook_name, mixed $arg ) 将函数添加到指定挂钩的回调函数 action(动作)。 此函数调用附加到动作钩子的所有函数$hook_name。可以通过简单地调用这...
-
17
How to add section header and footer to SwiftUI list 16 May 2022 ⋅ 7 min read ⋅ Sw...
-
7
Works great, thanks. You need to run the following command: sudo gem install rb-appscript. Would be nice to make a Chrome extension....
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK