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

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

问题描述

恐怕这是一个非常愚蠢的问题,但我一定错过了什么.

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

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

文档说方法

创建一个新的 String 实例与指定字符串相同的值.

Creates a new instance of String with the same value as a specified 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 的事实之外,没有可观察到的差异 - String 是一个不可变类,其相等性基于值,而不是身份.(感谢@Andrew Hare 指出我最初的措辞不够精确,无法表明我意识到 Copying 和 not 之间存在差异,但担心感觉缺乏 有用的区别.)

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.)

当然,当传递 null 参数时,Copy 会抛出 ArgumentNullException,并且新实例"可能会消耗更多内存.后者似乎几乎没有好处,而且我不确定 null 检查是否足以保证整个 Copy 方法.

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 实际上是在分配新内存并将字符从一个字符串复制到另一个字符串;你得到一个全新的实例,而不是让两个变量都是同一个实例.如果您将字符串与直接处理内存位置并可以改变字符串的非托管代码一起使用,这可能很重要.

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.

这篇关于System.String.Copy 在 .NET 中有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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