关于C#中传值和传引用的概念,我有一个有关深拷贝和浅拷贝的一般性问题:
C#中需要显式创建接受指针/引用的方法才能将其传递给该方法。但是,至少作为参数传递到方法/构造函数中的对象与其他对象的行为不同。如果没有进行额外的克隆,它们似乎总是以引用方式传递,如此处所述:http://zetcode.com/lang/csharp/oopii/。
为什么对象会自动以引用方式传递呢?在这些情况下,强制执行克隆过程是否比更像int、double、boolean等类型更具优势?
以下是说明我的代码示例:
using System;
public class Entry
{
public class MyColor
{
public int r = 0;
public int g = 0;
public int b = 0;
public double a = 1;
public MyColor (int r, int g, int b, double a)
{
this.r = r;
this.g = g;
this.b = b;
this.a = a;
}
}
public class A
{
public int id;
public MyColor color;
public MyColor hiddenColor;
public A (int id, MyColor color)
{
this.id = id;
this.color = color;
}
}
static void Main(string[] args)
{
int id = 0;
MyColor col = new MyColor(1, 2, 3, 1.0);
A a1 = new A(id, col);
A a2 = new A(id, col);
a1.hiddenColor = col;
a2.hiddenColor = col;
a1.id = -999;
id = 1;
col.a = 0;
Console.WriteLine(a1.id);
Console.WriteLine(a2.id);
Console.WriteLine(a1.color.a);
Console.WriteLine(a2.color.a);
Console.WriteLine(a1.hiddenColor.a);
Console.WriteLine(a2.hiddenColor.a);
}
}
这将导致:
-999
0
0
0
0
MyCol
的实例总是通过引用传递,而其他参数则通过值传递。我必须在类 MyColor
和 A
中实现 ICloneable 接口。另一方面,在 C# 中存在 ´ref´ 语句,应该使用它来明确允许并进行引用传递。
欢迎提出建议!