我有一节课,下面是:
public Person(string name, int age)
{
Name = name;
Age = age;
}
宣布课程后,我有以下内容:
String OtherName;
Int OtherAge;
Person jane = new Person("Jane", 28);
OtherName = Jane.Name;
OtherAge = Jane.Age;
如何更改OtherName
的值时,如何存储OtherAge
和jane
以及它们不会更改?
答案 0 :(得分:3)
即使OtherName
或其属性的值已更新,变量OtherAge
和jane
也会保留其值。
答案 1 :(得分:-2)
我在下面重构了Person类,如果名称改变,其他名称将会改变。但其他名称可能会改变,不会影响名称道具。
public class Person
{
public Person(string name, int age)
{
Name = name;
Age = age;
}
private string name;
public string Name
{
get { return name; }
set { otherName = name = value; }
}
private int age;
public int Age
{
get { return age; }
set { otherAge = age = value; }
}
private string otherName;
public string OtherName
{
get { return otherName; }
set { otherName = value; }
}
private int otherAge;
public int OtherAge
{
get { return otherAge; }
set { otherAge = value; }
}
}
示例:
static void Main(string[] args)
{
Person jane = new Person("Jane", 28);
jane.OtherName = jane.Name;
jane.OtherAge = jane.Age;
jane.Name = "Dave";
jane.Age = 30;
Console.WriteLine(jane.Name);
Console.WriteLine(jane.Age);
Console.WriteLine(jane.OtherName);
Console.WriteLine(jane.OtherAge);
Console.ReadKey();
}
输出: 戴夫 三十 戴夫 30