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

标签 c# string pointers memory clr

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

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

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/

相关文章:

c# - 群聊功能

java - 如何使警报对话框按 Java 中的位置显示字符串中的项目?

c++ - 为什么不能将 *pointer+offset 用作左值? ("error: non-lvalue in assignment")

c - 插入节点并按字母顺序排列

c# - 使用Redis实现登录?

c# - 可以采取哪些步骤来优化 ListView

c# - 我应该使用反射 (C#) 组合接口(interface)实现吗?

python - 更改大小写,除非它是 python 中的超链接

javascript - 如何在 javascript 中填充字符串长度?

c++ - 不能用大括号传递两次指针