New:
1. 作为运算符, 用于创建对象和调用构造函数。
2. 作为修饰符,用于向基类成员隐藏继承成员。
代码
public class A
{
public virtual void Method1()
{}
public virtual void Method2()
{}
public virtual void Method3()
{}
}
public class B : A
{
public new void Method1()
{}
public new void Method2()
{}
public override void Method3()
{}
}
public class Test
{
private static void Main()
{
A a = new B();
a.Method1(); //will call A's Method1
a.Method2(); //will call A's Method2
a.Method3(); //will call B's Method3
((B)a).Method1();
}
}
{
public virtual void Method1()
{}
public virtual void Method2()
{}
public virtual void Method3()
{}
}
public class B : A
{
public new void Method1()
{}
public new void Method2()
{}
public override void Method3()
{}
}
public class Test
{
private static void Main()
{
A a = new B();
a.Method1(); //will call A's Method1
a.Method2(); //will call A's Method2
a.Method3(); //will call B's Method3
((B)a).Method1();
}
}
3. 作为约束,用于在泛型声明中约束可能用作类型参数的参数的类型。
class Genericer<T> where T : new()
{
public T GetItem()
{
return new T();
}
}
{
public T GetItem()
{
return new T();
}
}