可以用与积累成员名称相同的成员来屏蔽
要让编译器知道你在故意屏蔽继承的成员,可以用new修饰符。否则程序可以成功编译,但是编译器会警告你隐藏了一个继承的成员
using System;class someClass
{public string F1 = "Someclass F1";public void M1(string f){Console.WriteLine($"someclass M1:{f}");}
}
class otherClass:someClass
{public string F1 = "otherClass F1";public void M1(string f){Console.WriteLine($"otherClass M1:{f}");}
}
public class Program
{public static void Main(string[] args){otherClass o = new otherClass();o.M1(o.F1);}
}
使用new:
using System;class someClass
{public string F1 = "Someclass F1";public void M1(string f){Console.WriteLine($"someclass M1:{f}");}
}
class otherClass:someClass
{new public string F1 = "otherClass F1";new public void M1(string f){Console.WriteLine($"otherClass M1:{f}");}
}
public class Program
{public static void Main(string[] args){otherClass o = new otherClass();o.M1(o.F1);}
}
结果:
otherClass M1:otherClass F1