{
public class Employee1
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
}
public class Manager : Employee1
{
private string name;
// Notice the use of the new modifier:
public new string Name
{
get { return name; }
set { name = value + ", Manager"; }
}
}
class TestHiding
{
static void Main()
{
Manager m1 = new Manager();
// Derived class property.
m1.Name = "John";
// Base class property.
((Employee1)m1).Name = "Mary";//将子类的引用转换成父类的引用此时调用的是父类的set属性
System.Console.WriteLine("Name in the derived class is: {0}", m1.Name);
System.Console.WriteLine("Name in the base class is: {0}", ((Employee1)m1).Name);//此时调用的是父类的get属性
}
}
}
当派生类的属性隐藏拉基类中的属性在子类中用new修饰符做说明;代码如下
public new string Name
{
get { return name; }
set { name = value + ", Manager"; }
}
注:父类和子类的中的字段可以是不同名称