“静态新"的含义是什么?功能的修饰符? [英] What is the point of "static new" modifier for a function?

查看:68
本文介绍了“静态新"的含义是什么?功能的修饰符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我在旧版代码中发现了一些东西.它具有一项功能的静态新功能".看起来像这样.

Today, I found something in legacy code. It has "static new" for one function. It looks like this.

class Foo
{
    public static void Do()
    {
        Console.WriteLine("Foo.Do");
    }
}

class Bar: Foo
{
    public static new void Do()
    {
        Console.WriteLine("Bar.Do");
    }
}

我不理解 Bar 类中 Do 方法的 静态新 修饰符.在C#中,只能使用类名而不是对象名来调用静态方法.因此,我认为拥有新"与没有新"之间没有任何区别.

I don't understand the static new modifier for the Do method in class Bar. In C#, static method can only be invoked with class name instead of object name. So, I don't think there is any difference between having the "new" and not.

通常,如果不需要某些语法,则C#会将其视为错误. 有人对为什么C#允许这种语法有任何想法吗?

Generally, if some syntax is unnecessary, C# just treat it is error. Anybody has any idea about why C# allows such syntax?

推荐答案

如果从代码中删除,则会得到:

If you remove the new from your code you get:

警告CS0108:"Bar.Do()"隐藏继承的成员"Foo.Do()".如果打算隐藏,请使用new关键字.

warning CS0108: 'Bar.Do()' hides inherited member 'Foo.Do()'. Use the new keyword if hiding was intended.

C#编译器只是警告您您可能正在做您不打算做的事情,并要求您插入 new 关键字以确认您知道自己在做什么.除了抑制警告之外,它没有其他作用.

The C# compiler just warns you that you might be doing something you did not intend and asks you to insert the new keyword to confirm that you know what you are doing. Besides suppressing the warning, it has no other effects.

这篇关于“静态新"的含义是什么?功能的修饰符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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