开发者

Set Object Property from other Object Property Question

开发者 https://www.devze.com 2023-03-15 11:56 出处:网络
I\'m very sorry if the Topic name doesnt match my problem. I was up to google it up, but I havn\'t any idea how my \"problem\" is called :(

I'm very sorry if the Topic name doesnt match my problem. I was up to google it up, but I havn't any idea how my "problem" is called :(

I think thats a really basic question, but I think it's important to understand. First of all I'll show the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            A a = new A();
            a.x = 5;
            a.y = 41;

            B b = new B();
            b.a = 14;
            b.b = a.y;
            b.c = a;

            a.x += 10;
            a.y -= 30;
        }
    }

    class A
    {
        public int x;
        public int y;
    }

    class B
    {
        public int a;
        public int b;
        public A c;
    }
}

I've got some very basic classes A and B. B can hold an instance of A. The "problem" I have, is: If a pass A to B and set a property of A (a.y -= 30;) the value of b.b also changes. How do I avoid that? I just want b.b to be the 开发者_运维问答value of a.y. But if a.y changes, b.b should not! Is the only way to do that, creating a Clone of the objects and then pass it?


Everything works as expected

Set Object Property from other Object Property Question


with

b.c = a;

you are passing a reference to an object.

to avoid this, you have to use a copy of the object. a clone, as you already recognized.


With a.y -= 30, b.b will not change. An int is a value-type, not a reference type.

(Your assumption is incorrect)

0

精彩评论

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

关注公众号