例如,
class Age
{
public int Year
{
get;
set;
}
public Age(int year)
{
Year = year;
}
}
class Person
{
public Age MyAge
{
get;
set;
}
public Person(Age age)
{
age.Year = ( age.Year * 2 );
MyAge = age;
}
}
[客户]
Age a = new Age(10);
Person p = new Person( a );
当构造一个新的Age
类时,Year
属性为:10。但是,Person类将Year更改为20,即使没有ref关键字......
有人可以解释为什么年份不是10岁?
答案 0 :(得分:2)
通过值传递对象的引用。使用该引用,可以修改对象实例本身。
请考虑以下示例以了解该陈述的含义:
public class A
{
private MyClass my = new MyClass();
public void Do()
{
TryToChangeInstance(my);
DoChangeInstance(my);
DoChangeProperty(my);
}
private void TryToChangeInstance(MyClass my)
{
// The copy of the reference is replaced with a new reference.
// The instance assigned to my goes out of scope when the method exits.
// The original instance is unaffected.
my = new MyClass();
}
private void DoChangeInstance(ref MyClass my)
{
// A reference to the reference was passed in
// The original instance is replaced by the new instance.
my = new MyClass();
}
private void DoChangeProperty(MyClass my)
{
my.SomeProperty = 42; // This change survives the method exit.
}
}
答案 1 :(得分:-1)
因为Age
是引用类型。