Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
425 views
in Technique[技术] by (71.8m points)

c# - 请向我解释为什么它不分配副本,而是分配指针? C#[重复](Please explain to me why this does not assign a copy, but a pointer? C# [duplicate])

This is the program in question:

(这是有问题的程序:)

namespace TestStuff
{
    public class Test
    {
        public int x;
    }
    class Program
    {
        static void Main(string[] args)
        {
            Test firstClass = new Test();
            firstClass.x = 5;
            Test secondClass = firstClass;
            firstClass.x = 6;
            Console.WriteLine(secondClass.x);

        }
    }
}

The output of this program is 6, I assume this is because Test secondClass = firstClass;

(该程序的输出为6,我认为这是因为Test secondClass = firstClass;)

, makes secondClass point to firstClass instead of making a copy of firstClass.

(,使secondClass指向firstClass,而不是复制firstClass。)

If i want to make secondClass a copy of firstClass, how would I go about that ?

(如果我想将secondClass复制为firstClass的副本,该如何处理?)

  ask by victorfaarvang translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I guess it's an OOP (Object-Oriented Programming) misconception.

(我猜这是一个OOP(面向对象编程)的误解。)

Although Test.x is an int (thus a value type) and, if copied around, you wouldn't get a reference for it, in this case, you're copying the whole Test instance from firstClass to secondClass .

(尽管Test.x是一个int (因此是一个值类型),并且如果被四处复制,您将不会得到它的引用,在这种情况下,您是将整个Test实例从firstClass复制到secondClass 。)

Test secondClass = firstClass; will make both "references" being the same object and by modifying firstClass.x you'll also update secondClass.x .

(将使两个“引用”成为同一对象,并且通过修改firstClass.x您还将更新secondClass.x 。)

It's not because of .x , but because firstClass and secondClass are both the same instance of object.

(这不是因为.x ,而是因为firstClasssecondClass都是对象的相同实例。)

If i want to make secondClass a copy of firstClass, how would I go about that?

(如果我想将secondClass复制为firstClass的副本,该如何处理?)

In order to achieve this, you need to clone the object, instead.

(为了实现这一点,您需要克隆对象。)

https://stackoverflow.com/a/129395/1256062 might be a good source for it.

(https://stackoverflow.com/a/129395/1256062可能是一个很好的来源。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...