从其他对象属性设置对象属性问题
如果主题名称与我的问题不匹配,我很抱歉。我准备用谷歌搜索它,但我不知道我的“问题”是如何称呼的:(
我认为这是一个非常基本的问题,但我认为理解它很重要。 首先,我将展示代码:
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;
}
}
我有一些非常基本的类 A 和 B。B 可以保存 A 的实例。我遇到的“问题”是: 如果 a 将 A 传递给 B 并设置 A 的属性 (ay -= 30;
),则 bb
的值也会更改。我该如何避免这种情况? 我只想将 bb 设为 ay 的值。但如果 ay
发生变化,bb
就不应该发生变化! 创建对象的克隆然后传递它是唯一的方法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一切按预期工作
Everything works as expected
其中
bc = a;
您正在传递对对象的引用。
为了避免这种情况,您必须使用该对象的副本。一个克隆,正如你已经认识到的那样。
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.
当
ay -= 30
时,bb
不会改变。int
是值类型,而不是引用类型。(你的假设是错误的)
With
a.y -= 30
,b.b
will not change. Anint
is a value-type, not a reference type.(Your assumption is incorrect)