开发者

Assigning a variable of a struct that contains an instance of a class to another variable

开发者 https://www.devze.com 2023-03-15 07:51 出处:网络
In my understanding, 开发者_如何学Cassigning a variable of a struct to another variable of the same type will make a copy. But this rule seems broken as shown on the following figure. Could you explai

In my understanding, 开发者_如何学Cassigning a variable of a struct to another variable of the same type will make a copy. But this rule seems broken as shown on the following figure. Could you explain why this happened?

Assigning a variable of a struct that contains an instance of a class to another variable

using System;

namespace ReferenceInValue
{
    class Inner
    {
        public int data;
        public Inner(int data) { this.data = data; }
    }

    struct Outer
    {
        public Inner inner;
        public Outer(int data) { this.inner = new Inner(data); }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Outer p1 = new Outer(1);
            Outer p2 = p1;
            Console.WriteLine("p1:{0}, p2:{1}", p1.inner.data, p2.inner.data);


            p1.inner.data = 2;
            Console.WriteLine("p1:{0}, p2:{1}", p1.inner.data, p2.inner.data);


            p2.inner.data = 3;
            Console.WriteLine("p1:{0}, p2:{1}", p1.inner.data, p2.inner.data);

            Console.ReadKey();
        }
    }
}


You answered your question in the topic.

Your structure contains a reference, when the structure is copied, it is copied as a chunk of memory, including the reference (not the object that is referenced), just as if the reference was an integer or another primitive.

Copying a structure does not cause cloning.

In fact, placing a reference in a structure is a bad idea and should be avoided. An exception to this is immutable reference objects (such as strings), which are "safe" to place in structures, since they can not be modified, however you will still loose locality in memory.

Remember, value types are stored locally in the scope of their definition, reference types are always stored on heap and a reference is stored locally in the scope of their definition.


Adding to what the others have said : If you need to convince yourself that p1.inner and p2.inner are indeed pointing to the same class instance, you can run code like this :

Console.WriteLine("ReferenceEquals:{0}", object.ReferenceEquals(p1.inner, p2.inner));

If you run this anytime after the line "Outer p2 = p1;", it will always write : "ReferenceEquals:True".


P1 and P2 both are pointing to one object of type Inner... That's why values are the same...


struct Outer
{
   public Inner inner;
   public Outer(int data) { this.inner = new Inner(data); }

   public Clone() { return new Outer(this.inner.data); }
}

now try using the code like so:


...
 p2 = p1.Clone();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号