new在c#中有三种用法:
1.实例化对象
2.泛型约束
3.用在方法前。new和override的区别在于:override用于重写父类的方法;new用于隐藏方法,它调用的方法来自于申明的类,如果申明的是父类,调用父类方法,声明的是子类,则调用子类的方法,如果申明的对象时匿名的,则默认调用子类的方法。
public class New_Study
{
public virtual void Method1()
{
Console.WriteLine("PMethod1");
}
public virtual void Method2()
{
Console.WriteLine("PMethod2");
}
}
public class ChildClass:New_Study
{
public override void Method1()
{
Console.WriteLine("override CMethod1");
}
public new void Method2()
{
Console.WriteLine("new CMethod2");
}
}
[TestFixture]
public class New_Study_Test
{
[Test]
public void TestNew()
{
New_Study parent1 = new ChildClass();
parent1.Method1();//override CMethod1
parent1.Method2();//PMethod2
ChildClass child=new ChildClass();
child.Method1();//override CMethod1
child.Method2();//new CMethod2
var varTest = new ChildClass();
varTest.Method1();//override CMethod1
varTest.Method2();//new CMethod2
}
}
来源:https://www.cnblogs.com/wanghonghu/p/5270838.html