当(深)的克隆,使用String.Copy或STR1 = STR2? [英] When (deep) Cloning, use String.Copy or str1 = str2?

查看:96
本文介绍了当(深)的克隆,使用String.Copy或STR1 = STR2?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在(深)克隆自定义对象,我应该用 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.

这篇关于当(深)的克隆,使用String.Copy或STR1 = STR2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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