如何在C#中获取字符串的内存地址?

Der*_*van 3 c#

有人可以告诉我string在C#中获取a的内存地址的方法吗?例如,在:

string a = "qwer";
Run Code Online (Sandbox Code Playgroud)

我需要获取的内存地址a

wes*_*ton 6

让我们来看看您感到惊讶的情况:

string a = "abc";
string b = a;
a = "def";
Console.WriteLine(b); //"abc" why?
Run Code Online (Sandbox Code Playgroud)

a并且b是对字符串的引用。涉及的实际字符串为"abc""def"

string a = "abc";
string b = a;
Run Code Online (Sandbox Code Playgroud)

双方ab都以相同的字符串引用"abc"

a = "def";
Run Code Online (Sandbox Code Playgroud)

现在a是对新字符串的引用"def",但是我们并没有做任何改变b,因此仍然在引用"abc"

Console.writeline(b); // "abc"
Run Code Online (Sandbox Code Playgroud)

如果我对int做同样的事情,您应该不会感到惊讶:

int a = 123;
int b = a;
a = 456;
Console.WriteLine(b); //123
Run Code Online (Sandbox Code Playgroud)

比较参考

现在您已经理解ab成为参考,您可以使用Object.ReferenceEquals

Object.ReferenceEquals(a, b) //true only if they reference the same exact string in memory
Run Code Online (Sandbox Code Playgroud)


小智 5

您需要使用fixed关键字在内存中修复字符串,然后使用char *引用内存地址。

using System;

class Program
{
    static void Main()
    {
        Console.WriteLine(Transform());
        Console.WriteLine(Transform());
        Console.WriteLine(Transform());
    }

    unsafe static string Transform()
    {
        // Get random string.
        string value = System.IO.Path.GetRandomFileName();

        // Use fixed statement on a char pointer.
        // ... The pointer now points to memory that won't be moved!
        fixed (char* pointer = value)
        {
            // Add one to each of the characters.
            for (int i = 0; pointer[i] != '\0'; ++i)
            {
                pointer[i]++;
            }
            // Return the mutated string.
            return new string(pointer);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

输出量

** 61c4eu6h / zt1

ctqqu62e / r2v

gb {kvhn6 / xwq **