public class Father
{
public Father()
{
// // TODO: 在此处添加构造函数逻辑 //
}
public int a = 1;
public int b()
{
return this.a;
}
}
public class Son:Father{
public Son()
{
// // TODO: 在此处添加构造函数逻辑 //
}
public int a = 2;
}
调用:
Son s = new Son();
int r = s.b();
Console.WriteLine(r);
为什么是1不是2啊 我已经在sun中重写了啊.
1. 只有方法的重载,没有数据成员的重载,数据成员只有继承关系。
2. 类的封闭性决定了类的方法只能访问类自身的数据成员。 3. 要实现你的目的,对父类的方法C用virtual修饰,然后在子类中用override重写。 |
class Program
{
static void Main(string[] args)
{
Son s = new Son();
int r = s.b();
Console.WriteLine(r);
Console.ReadKey();
}
}
public class Father
{
public Father()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
public int a = 1;
public virtual int b()
{
return this.a;
}
}
public class Son : Father
{
public Son()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
public int a = 2;
public override int b()
{
return this.a;
}
// public new int a = 2;
}