c# - 在 C# 中使用 new 关键字

标签 c# .net inheritance

<分区>

我有两个类(class)

class  A
{
     public virtual void Metod1()
     {
         Console.WriteLine("A.Method1");
     }
}

class B : A
{
    public new void  Metod1()
    {
        Console.WriteLine("B.Method1");
    }
}

然后我写一些代码来声明这些类的实例,并调用它们的方法

     static void Main(string[] args)
    {
        A a = new B();
        a.Metod1();
        B b = new B();
        b.Metod1();
        Console.ReadKey();
    }

我给出了以下结果:

A.Method1
B.Method1

但是当我从类 B 的签名方法 1 中删除关键字 new 并运行 Main 方法时,我得到了相同的结果。 问题:方法签名中的新关键字是否只是为了更好的可读性?

编辑:是否存在我们不能没有新关键字的情况?

最佳答案

new 关键字让代码阅读者知道此方法将隐藏其基类中具有相同名称的方法。即使您忽略了它,编译器也会以同样的方式对待它,但会警告您。

由于您将该方法声明为virtual,因此您在编译时会收到此警告:

'B.Metod1()' hides inherited member 'A.Metod1()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.

但是,如果您通过删除 virtual 来更改声明:

  • A

    中没有virtual 的声明
    class A {
        public void Metod1() {
            Console.WriteLine("A.Method1");
        }
    }
    
    class B: A {
        public void Metod1() {
            Console.WriteLine("B.Method1");
        }
    }
    

仍会编译,但警告消息将是:

'B.Metod1()' hides inherited member 'A.Metod1()'. Use the new keyword if hiding was intended.

以上述任一方式,如下:

  • 测试代码

    var b=new B();
    b.Metod1();
    (b as A).Metod1();
    

将输出:

B.Method1
A.Method1

But, if you declare as the following:

  • Declaration with override in B

    class A {
        public virtual void Metod1() {
            Console.WriteLine("A.Method1");
        }
    }
    
    class B: A {
        public override void Metod1() {
            Console.WriteLine("B.Method1");
        }
    }
    

那么输出将是:

B.Method1
B.Method1

That is because Method1 of the base class is not just hidden but overridden by the derived class.

A case that you cannot just use new is that if Method1 is a abstract method in a abstract class:

  • Code that must use override in derived classes

    abstract class A {
        public abstract void Metod1();
    }
    
    class B: A {
        public override void Metod1() { // use `new` instead of `override` would not compile
            Console.WriteLine("B.Method1");
        }
    }
    

在这种情况下,您不能只使用 new,因为 A 需要派生类来覆盖 Method1

关于c# - 在 C# 中使用 new 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15803965/

相关文章:

c# - 开发 WPF 应用程序 - 有什么方法可以优化 .NET 安装?

c# - Marketplace 测试套件返回 "Unsupported API cannot be used by background agent"

c# - 在 C# 中使用 MySQL

C# 将位图转换为索引颜色格式

java - 从子类访问父类的私有(private)实例变量?

wpf - 确定是否继承了 WPF DependencyProperty 值

C# 7 模式匹配语义

.net - 创建模板时如何在Elasticsearch.Net/NEST中设置Alias.is_write_index

c++ - 虚拟成员类的调用方法

.net - VB.Net 编码指南