我得到了virtual/override和new修饰符之间的区别.但是当我没有指定任何修饰符的时候呢.
例如,我有Animal和Cat类(Cat继承Animal).
Animal class有方法:
public void Say()
{
// do something
}
Run Code Online (Sandbox Code Playgroud)
并且Cat类有方法:
public void Say()
{
// do something else
}
Run Code Online (Sandbox Code Playgroud)
当我使用这种方法时,它们就好像我使用了new关键字一样.
Visual Studio向我显示警告(如果要隐藏,请使用新关键字).
当我没有指定关键字时,为什么编译器不会中断.它只是神奇地用了一点警告.我可以使用某些严格模式,也可以在IDE中编辑设置.
或者可能是我没有得到的功能:)
例如,
public class Foo
{
public virtual bool DoSomething() { return false; }
}
public class Bar : Foo
{
public override bool DoSomething() { return true; }
}
public class Test
{
public static void Main()
{
Foo test = new Bar();
Console.WriteLine(test.DoSomething());
}
}
Run Code Online (Sandbox Code Playgroud)
为什么答案是真的?"新酒吧()"是什么意思?"new Bar()"是不是意味着分配内存?
class A {
public virtual void M() { Console.Write("A"); }
}
class B: A {
public override void M() { Console.Write("B"); }
}
class C: B {
new public virtual void M() { Console.Write("C"); }
}
class D: C {
public override void M() { Console.Write("D"); }
static void Main() {
D d = new D();
C c = d;
B b = c;
A a = b;
d.M(); c.M(); b.M(); a.M();
}
}
Run Code Online (Sandbox Code Playgroud)
我是这个概念的新手,所以详细的答案将不胜感激.