在C#中使用new关键字 [英] Use new keyword in c#

查看:149
本文介绍了在C#中使用new关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个班

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

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

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

Then I write some code that declares instances of these classes, and calls their methods

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

我给了下面的结果:

I gave following result:

A.Method1
B.Method1

但是,当我删除的关键字新的B级的签名方法1和运行的主要方法我得到了相同的结果。 问:是否在方法签名新的关键字只为更好的可读性

But when I delete keyword new from signature method1 of class B and run Main method I got same result. Question:Is new keyword in signature of methods only for better readability?

编辑:是否有情况下,我们不能没有一个新的关键字?

Are there cases where we can not do without a new keyword?

推荐答案

是的,你是正确的,它是在这种情况下更好的可读性。

Yes, you are correct, it is for better readability in this situation.

但仔细检查,你应该不使用新的藏身基方法,当一个警告。

But check carefully you should have a warning for not using new when hiding the base method.

您可以在这里阅读更多: http://msdn.microsoft.com/en-us/library/vstudio /435f1dw2.aspx

You can read more here: http://msdn.microsoft.com/en-us/library/vstudio/435f1dw2.aspx

这篇关于在C#中使用new关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆