gpt4 book ai didi

C# - String Clone() 和 Copy() 方法有什么区别

转载 作者:行者123 更新时间:2023-12-02 15:49:16 27 4
gpt4 key购买 nike

我想知道如果 Copy() 和 Clone() 方法执行相同的任务,它们之间有什么区别以及使用哪一个

根据我搜索到的内容,clone() 会创建一个新字符串,而 copy() 只是复制现有字符串并使用它

如果这是正确的,那么哪个更好

最佳答案

TL;博士:

不要使用这两种方法:

  • Clone 实际上没有做任何事情
  • Copy 已正式过时

等等:

我将这样说作为我的回答的序言,因为 String值是不可变的,使用 String.Clone() 并没有太多(或任何?)好的理由。或String.Copy .

as per what i have searched aboout is that clone() makes a new string and copy() just do copy an existing string and use it

抱歉,您的理解不正确。

根据文档(强调我的):

String.Clone() 创建字符串的副本,实际上它只是返回一个自引用:

https://learn.microsoft.com/en-us/dotnet/api/system.string.clone?view=net-6.0

The return value is not an independent copy of this instance; it is simply another view of the same data. Use the Copy or CopyTo method to create a separate String object with the same value as this instance.

Because the Clone method simply returns the existing string instance, there is little reason to call it directly.

至于String.Copy() :

https://learn.microsoft.com/en-us/dotnet/api/system.string.copy?view=net-6.0

The Copy method returns a String object that has the same value as the original string but represents a different object reference.

[...]

Starting with .NET Core 3.0, this method is obsolete. However, we do not recommend its use in any .NET implementation. In particular, because of changes in string interning in .NET Core 3.0, in some cases the Copy method will not create a new string but will simply return a reference to an existing interned string.

此外,因为 String.Copy 可能创建一个副本(取决于实习的工作方式)_这意味着它是 O(n)操作。

关于C# - String Clone() 和 Copy() 方法有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73075377/

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