gpt4 book ai didi

c# - 为什么 C# 在这种情况下使用相同的内存地址?

转载 作者:太空狗 更新时间:2023-10-29 21:07:45 24 4
gpt4 key购买 nike

当我执行这段代码时

class Program
{
static void Main(string[] args)
{
//scope 1
{
string x = "shark";
string y = x.Substring(0);
unsafe
{
fixed (char* c = y)
{
c[4] = 'p';
}
}
Console.WriteLine(x);
}
//scope 2
{
string x = "shark";
//Why output in this line "sharp" and not "shark" ?
Console.WriteLine(x);
}
}
}

输出是:

sharp
sharp

当我在这样的方法中分离这 2 个范围时:

class Program
{
static void Main(string[] args)
{
func1();
func2();
}
private static void func2()
{
{
string x = "shark";
Console.WriteLine(x);
}
}

private static void func1()
{
{
string x = "shark";
string y = x.Substring(0);
unsafe
{
fixed (char* c = y)
{
c[4] = 'p';
}
}
Console.WriteLine(x);
}
}
}

输出是:

sharp
shark

已编辑

我也尝试过这种方式:

  class Program
{
static void Main(string[] args)
{
{
string x = "shark";
string y = x.Substring(0);
unsafe
{
fixed (char* c = y)
{
c[4] = 'p';
}
}
Console.WriteLine(x);
}
void Test(){
{
string x = "shark";
Console.WriteLine(x);
}
}
Test();
}
}

输出为:

 sharp
shark

**我使用的环境是MacOS和.net core 2.2 (Rider) **

我希望在所有情况下都有相同的输出,但输出不同。正如我们所知,实习是将您硬编码的所有字符串放入汇编中并在整个应用程序中全局重用以重用相同的内存空间。但是在这段代码的情况下,我们看到了

硬编码字符串仅在函数范围内重用,而不在全局范围内重用

这是 .NET Core 错误还是有解释?

enter image description here enter image description here

最佳答案

请注意自从我写这篇文章以来问题已经改变

如果您查看 source .

if( startIndex == 0 && length == this.Length) {
return this;
}

所以当你使用 Substring(0)你得到一个对原件的引用,然后用unsafe变异

在第二个例子中Substring(1)正在分配 string .


更深入的分析。

string x = "shark";
string y = x.Substring(0);
// x reference and y reference are pointing to the same place

// then you mutate the one memory
c[4] = 'p';

// second scope
string x = "shark";
string y = x.Substring(1);
// x reference and y reference are differnt

// you are mutating y
c[0] = 'p';

编辑

stringinterened,并且编译器认为 "shark" 的任何文字是相同的(通过散列)。这就是为什么第二部分即使使用不同的变量也会产生变异的结果

String interning refers to having a single copy of each unique string in an string intern pool, which is via a hash table in the.NET common language runtime (CLR). Where the key is a hash of the string and the value is a reference to the actual String object

调试第二部分(有无作用域和变量不同)

enter image description here

编辑2

范围对我、框架或核心都无关紧要,它总是产生相同的结果(第一个),它很可能是一个实现细节,并且在规范中模糊定义了内部的性质

关于c# - 为什么 C# 在这种情况下使用相同的内存地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57603511/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com