Why does String.Clone() returns the original string and not a copy of it?

后端 未结 3 1398
轻奢々
轻奢々 2021-02-18 17:40

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

3条回答
  •  忘了有多久
    2021-02-18 18:18

    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.

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

提交回复
热议问题