问题描述
我恐怕这是一个非常愚蠢的问题,但我一定是失去了一些东西。
I'm afraid that this is a very silly question, but I must be missing something.
为什么也许有希望使用 String.Copy(串)?
Why might one want to use String.Copy(string)?
该文件说,该方法
创建一个字符串的一个新的实例 相同的值作为指定String
由于字符串是不可变的。NET,我不知道什么是使用这种方法的好处,因为我觉得
Since strings are immutable in .NET, I'm not sure what's the benefit of using this method, as I'd think that
string copy = String.Copy(otherString);
将所有的实际目的似乎得到相同的结果
would for all practical purposes seem to yield the same result as
string copy = otherString;
也就是说,除了出于某种内部簿记这回事,并且复制事实并非的ReferenceEquals
来otherString,没有观察到差异 - 字符串是一个不可变类其平等基础上的价值,而不是身份。(感谢@ 安德鲁野兔的指出我原来的措辞并不precise足以表明,我意识到有复制之间的差异
荷兰国际集团,而不是,但关注的是,认为缺乏的有用的区别。)
That is, except for whatever internal bookkeeping that's going on, and the fact that copy is not ReferenceEquals
to otherString, there are no observable differences - String being an immutable class whose equality is based on value, not identity.(Thanks to @Andrew Hare for pointing out that my original phrasing was not precise enough to indicate that I realized there was a difference between Copy
ing and not, but was concerned about the perceived lack of useful difference.)
当然,如果通过了空
参数,复制抛出一个 ArgumentNullException
,和新情况可能消耗更多的内存。后者似乎很难像一个好处,我不知道,空检查是一个足够大的奖金,以保证整个复制的方法。
Of course when passed a null
argument, Copy throws an ArgumentNullException
, and the "new instance" might consume more memory. The latter hardly seems like a benefit, and I'm not sure that the null check is a big enough bonus to warrant a whole Copy method.
感谢。
推荐答案
通过String.Copy你实际上是在分配新的内存并复制的字符从一个字符串到另一个;你得到一个完全新的实例,而不是具有两个变量是相同的实例。如果您使用的字符串与非托管code其中涉及直接存储器位置,可以发生变异的字符串,这可能没关系。
With String.Copy you are actually allocating new memory and copying the characters from one string to another; you get a completely new instance as opposed to having both variables being the same instance. This may matter if you use the string with unmanaged code which deals with the memory locations directly and can mutate the string.
这篇关于什么是在.NET中使用System.String.Copy的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!