.NET中System.String.Copy的用途是什么? [英] What's the use of System.String.Copy in .NET?

查看:172
本文介绍了.NET中System.String.Copy的用途是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我恐怕这是一个非常愚蠢的问题,但我必须缺少一些东西。



为什么要使用 String.Copy(string)



文档说明方法


使用
创建一个String的新实例与指定String的值相同。


由于字符串在.NET中是不可变的,我不知道使用这个方法的好处是什么,

  string copy = String.Copy(otherString); 

对于所有实际用途,似乎产生与

相同的结果

  string copy = otherString; 

也就是说,除了正在进行的内部记账以外, c $ c> ReferenceEquals 到otherString,没有可观察到的差异 - String是一个不可变的类,其相等性基于值,而不是身份。
(感谢@Andrew Hare指出我的原始短语不够精确,表明我意识到复制 ing和不是有区别,但是)

当然,当传递 null 时, c>参数,Copy引发一个 ArgumentNullException ,并且新实例可能消耗更多的内存。后者几乎不是一个好处,我不能确定null检查是一个足够大的奖金,以保证一个完整的复制方法。



谢谢。 >

解决方案

使用String.Copy,你实际上是分配新的内存并将字符从一个字符串复制到另一个字符串;你得到一个全新的实例,而不是让两个变量是同一个实例。如果您使用带有非托管代码的字符串直接处理内存位置并可以更改字符串,这可能很重要。


I'm afraid that this is a very silly question, but I must be missing something.

Why might one want to use String.Copy(string)?

The documentation says the method

Creates a new instance of String with the same value as a specified String.

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;

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 Copying and not, but was concerned about the perceived lack of useful difference.)

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.

Thanks.

解决方案

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的用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆