我目前正在学习 C#,在理解继承方面存在问题。 这是我的代码:
这是家长班:
class Member
{
protected int annualFee; // protected field =only accessible within the same class in which it is declared and any class derived from it
private string name; // private field = can be accesed of the same class or struct
private int memberId;
private int memberSince;
// writing ToString() method to display the values of the four fields
public override string ToString()
{
return "\nName: " + name + "\nMember ID: " + memberId + "\nMember Since: " + memberSince + "\nTotal Annual Fee: " + annualFee;
}
// adding two constructors to the member class
public Member()
{
Console.WriteLine("Parent Constructor with no parameter");
}
public Member(string pName, int pMemberID, int pMemberSince)
{
Console.WriteLine("Parent Constructor with 3 parameters");
name = pName;
memberId = pMemberID;
memberSince = pMemberSince;
Console.WriteLine("Parent Constructor:" + name + ", " + memberId + ", " + memberSince);
}
}
这是子班:
class VIPMember : Member
{
public VIPMember(string name, int memberId, int memberSince) : base (name, memberId, memberSince)
{
Console.WriteLine("Child constructor with 3 paramemters");
}
public void CalculateAnnualFee()
{
annualFee = 1200 * 2 + 12 * 30; //ans = 2760
}
public int annualFee = 120000; // field inherit from parent class, will overwrite annual fee in CalculateAnnualfee() method
}
创建子类的实例并调用构造函数和方法。
class ClassDemo
{
static void Main(string[] args)
{
VIPMember myChildMember2 = new VIPMember("Andy", 2, 2011);
myChildMember2.CalculateAnnualFee(); // method from child class VIPMember
Console.WriteLine(myChildMember2.ToString()); // method inherit from parent class Member
Console.WriteLine("Field from VIPMember (protected to public) class: " + myChildMember2.annualFee);
}
}
答案:
Parent Constructor with 3 parameters
Parent Constructor:Andy, 2, 2011
Child constructor with 3 paramemters
Name: Andy
Member ID: 2
Member Since: 2011
Total Annual Fee: 0
Field from VIPMember (protected to public) class: 2760
我特意添加了 public int AnnualFee = 120000 字段来尝试一下。然而,输出并不是我所期望的。我很期待:
Total Annual Fee: 2760
Field from VIPMember (protected to public) class: 12000
有人可以解释一下背后的逻辑吗?
谢谢你。
当您在
public int annualFee
中定义 VIPMember
时,您会 遮蔽 中的 protected int annualFee
。您有效地创建了一个具有相同名称的全新字段,并使您只能从定义它的类中看到 Member
。编译器应该向您发出警告,表明您正在这样做。试试这个:
annualFee
你得到:
void Main()
{
B b = new B();
Console.WriteLine(b.x);
b.x = 3;
Console.WriteLine(b.x);
A a = b;
Console.WriteLine(a.x);
a.x = 4;
Console.WriteLine(a.x);
}
public class A
{
public int x = 1;
}
public class B : A
{
public int x = 2;
}
但是如果我没有被跟踪
2
3
1
4
那么我会这样编写代码:
x
请注意,我需要在
void Main()
{
B b = new B();
Console.WriteLine(b.x);
b.x = 3;
Console.WriteLine(b.x);
A a = b;
Console.WriteLine(a.x);
a.x = 4;
Console.WriteLine(a.x);
Console.WriteLine(b.x);
}
public class A
{
public int x = 1;
}
public class B : A
{
public B()
{
this.x = 2;
}
}
的构造函数中更新
x
。要重写你的代码,你应该这样做:
B
然后它就如你所期望的那样工作了。