c# - 对象引用行为

标签 c# c#-4.0

在下面的代码片段中,我有两个变量firstStringsecondString,它们具有相同的值“Hello”。所以两个变量的引用位置是相同的。

var firstString = "Hello";
var secondString = "Hello";
bool isSameReference = Object.ReferenceEquals(firstString, secondString);
//same reference for both variables

但是将 secondString 值更新为 "Hey" 不会更新 firstString,即使它引用相同的位置。为什么这些引用相同引用位置的变量没有得到更新?

secondString = "Hey..";
isSameReference = Object.ReferenceEquals(firstString, secondString); 
//reference changed but firstString not updated

secondString 更新为之前的值,如 “Hello” 使引用相同。

secondString = "Hello";
isSameReference = Object.ReferenceEquals(firstString, secondString); 
//now the reference for both variables are same

为什么 c# 有这种行为以及 frmaework 内部如何处理这种情况?提前致谢

最佳答案

这个过程称为实习。您可以阅读有关字符串实习的更多信息 there 。当分配与现有字符串完全相同的新字符串时,这可以节省一些空间和处理时间。此外,刺痛实习使字符串比较变得微不足道。这是可能的,因为 String 是不可变类型。

关于c# - 对象引用行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18575684/

相关文章:

java - 构建Antlr时,Visual Studio在未命名文件的情况下给出错误 "cannot find the file specified"

Java 中 getBytes 的 C# 模拟

.net - 如何在 Asp.net web Api 2 中使用多个 Put 和 Post 方法

winforms - 手动向 DataGridView 添加新行不会立即更新绑定(bind)的 DataTable

c# - 用于选择下一个兄弟的 Xpath

c# - Entity Framework Core 3.0 查询导致 "SqlException: ' Execution Timeout Expired'"和 tempdb 变满。适用于 EF Core 2.2.6

c# - Winform 自定义控件 : DesignMode doesn't return true whereas in Design Mode

ios - PushSharp Push 在停止之前不会处理队列

winforms - 在 WinForms 中验证用户身份(与 ASP.Net 无关)

.net - Entity Framework 中的对象图是什么