gpt4 book ai didi

c# - Object.ReferenceEquals 为匹配的字符串返回 true

转载 作者:行者123 更新时间:2023-11-30 20:50:47 27 4
gpt4 key购买 nike

我正在使用 Mono,在比较两个字符串的引用时遇到了一个有趣的结果。下面的代码演示了一个例子:

using System;

class Program
{
static void Main()
{
String s1 = "asd";
String s2 = "asd";
Console.WriteLine("Reference Equals: {0}", Object.ReferenceEquals(s1, s2));

Console.ReadLine();
}
}

为真

有趣的是,两个字符串具有相同的值,但显然它们指的是两个不同的实例。这是怎么回事?

mono --version : Mono JIT 编译器版本 3.2.6OS X 10.9.2

最佳答案

http://msdn.microsoft.com/en-us/library/system.string.intern.aspx

The common language runtime conserves string storage by maintaining a table, called the intern pool, that contains a single reference to each unique literal string declared or created programmatically in your program. Consequently, an instance of a literal string with a particular value only exists once in the system.

下面显示了当字符串不是从 string literal 创建时的行为.

    static void Main(string[] args)
{
var string1 = new string(new []{'c'});
var string2 = new string(new []{'c'});
Console.WriteLine(string1.Equals(string2)); //true
Console.WriteLine(Object.ReferenceEquals(string1,string2)); //false
}

关于c# - Object.ReferenceEquals 为匹配的字符串返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22290576/

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