为什么String.Clone()返回原始字符串而不是它的副本? [英] Why does String.Clone() returns the original string and not a copy of it?

查看:41
本文介绍了为什么String.Clone()返回原始字符串而不是它的副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

令人惊讶的是, String.Clone()不会像 String.Copy()那样返回字符串的副本.而是返回'this',即原始字符串.

Surprisingly, String.Clone() doesn't return a copy of a string as String.Copy() would do. Instead, it returns 'this', the original string.

我想了解为什么.Net Framework团队选择采用这种方式.

I would like to understand why the .Net Framework team choose to go this way.

根据 MSDN :

ICloneable接口[...]要求您实现Clone方法返回当前对象实例的副本.

The ICloneable interface [...] requires that your implementation of the Clone method return a copy of the current object instance.

String.Clone()显然不遵循该准则.

我知道字符串是不可变的,但是如果这里不可变是原因,那么 String.Copy()也会返回 this ,但不是.

I know that strings are immutable, but if immutability was the reason here, String.Copy() would also return this but it doesn't.

这当然是一个理论问题.

This is a rather theoretical question, of course.

推荐答案

您如何发现差异?仅通过使用 object.ReferenceEquals 比较两个引用.但是通过对字符串的任何语义操作,您都无法分辨出差异.

How could you detect the difference? Only by comparing the two references using object.ReferenceEquals. But by any semantic operation on the string you can't tell the difference.

通过引用比较字符串几乎总是一个错误,因为您很少依赖于发生或不发生实习.

Comparing strings by reference is almost always a bug to begin with because you can rarely rely on interning to happen or not happen.

此问题不仅适用于 String .如果您有一个不变的 Point 类,为什么要从 Clone 返回一个新对象?不用.

This issue does not only apply to String. If you had an immutable Point class, why would you return a fresh object from Clone? No need.

IClonable 很少使用,也很少有用.如果要向类用户公开获取给定实例的副本的方法,则完全不需要从 IClonable 继承.

IClonable is rarely used and rarely useful, anyway. If you want to expose users of your class a way to obtain a copy of a given instance you don't need to inherit from IClonable at all.

这篇关于为什么String.Clone()返回原始字符串而不是它的副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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