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
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)
精彩评论