当(深)的克隆,使用String.Copy或STR1 = STR2?Copy、String

2023-09-03 15:14:12 作者:缠心绊情

在(深)克隆自定义对象,我应该用 clone.str1 = String.Copy(obj.str1) clone.str1 = obj.str1

When (deep) Cloning a custom object, should I use clone.str1 = String.Copy(obj.str1) or clone.str1 = obj.str1?

我倒是preFER后者 - 更短,更快,但它是安全的

I'd prefer the latter - shorter and quicker, but is it "safe"?

我会指向这个线程 ,但是,但是,不知道该用什么。

I'd point to this thread, but, however, not sure what to use.

推荐答案

是 - 后者选择(简单的分配)是安全的字符串(在托管code),因为这code说明:

Yes - the latter choice (simple assignment) is safe for strings (in managed code), as this code illustrates:

    string s1 = "Initial Value";
    string s2 = s1;

    Console.WriteLine("String1: " + s1);
    Console.WriteLine("String2: " + s2);

    s1 = "New Value";

    Console.WriteLine("String1 - after change: " + s1);
    Console.WriteLine("String2 - after change: " + s2);

输出:

String1: Initial Value
String2: Initial Value
String1 - after change: New Value
String2 - after change: Initial Value

字符串是不可变的 - 所以,当你改变S1,你真的创建一个新的字符串和分配它。 S2的引用仍然指向旧的实例。

Strings are immutable - so when you change s1, you are really creating a new string and assigning it. The reference of s2 remains pointing to the old instance.