gpt4 book ai didi

c# - 你能通过内存位置而不是内容来比较字符串吗?

转载 作者:行者123 更新时间:2023-11-30 14:11:07 24 4
gpt4 key购买 nike

我在某处读到,如果您的应用程序中有多个相同的字符串,那么实际上只会创建一个,并且所有引用都指向同一个字符串。

我在阅读有关锁的内容时看到有关此行为的警告。就像从不锁定字符串一样,因为应用程序中任何地方的任何其他锁定都可能锁定同一字符串。特别是如果你锁定了:

string lockObj = "";
...
{
lock(lockObj){
...
}
}

所以这让我想起了只有一个特定字符串的副本。所以如果我想比较两个字符串,有什么办法可以通过它们的内存位置来实现吗?喜欢..

public bool areSame(string s1,string s2){
return &s1 == &s2;
}

感谢您的帮助!

最佳答案

I read somewhere that if you have multiple strings in your application that are the same, that there is really only ever one created and all references really point to the same string.

这是不正确的。尽管您可以按照每个唯一字符串使用单个对象的方式安排程序,但 .NET 不提供此类保证。的确,C# 编译器将使程序中从字符串文字生成的所有 string 对象都指向同一个字符串对象。但是,创建具有相同内容的多个 string 对象相当容易。

if I wanted to compare two strings, is there any way to do it by their memory location?

您可以使用 Object.ReferenceEquals方法:

public bool areSame(string s1,string s2){
return Object.ReferenceEquals(s1, s2);
}

关于c# - 你能通过内存位置而不是内容来比较字符串吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21177565/

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