示例
在该例中,嵌套类 MyClass 隐藏了基类中具有相同名称的类。该例不仅说明了如何使用完全限定名访问隐藏类成员,同时也说明了如何使用 new 修饰符消除警告消息。
using System;
public class MyBaseC
{
public class MyClass
{
public int x = 200;
public int y;
}
}
public class MyDerivedC : MyBaseC
{
new public class MyClass // nested type hiding the base type members
{
public int x = 100;
public int y;
public int z;
}
public static void Main()
{
// Creating object from the overlapping class:
MyClass S1 = new MyClass();
// Creating object from the hidden class:
MyBaseC.MyClass S2 = new MyBaseC.MyClass();
Console.WriteLine(S1.x);
Console.WriteLine(S2.x);
}
}
public class MyBaseC
{
public class MyClass
{
public int x = 200;
public int y;
}
}
public class MyDerivedC : MyBaseC
{
new public class MyClass // nested type hiding the base type members
{
public int x = 100;
public int y;
public int z;
}
public static void Main()
{
// Creating object from the overlapping class:
MyClass S1 = new MyClass();
// Creating object from the hidden class:
MyBaseC.MyClass S2 = new MyBaseC.MyClass();
Console.WriteLine(S1.x);
Console.WriteLine(S2.x);
}
}
输出
100
200