在C#new修饰符 [英] new modifier in C#

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

问题描述

MSDN说:

当用作改性剂,在新的
关键字明确隐藏成员
继承从基类。当你
隐藏继承成员,该成员的派生
版本替换
基类的版本。虽然可以
隐藏部件在不使用
新改性剂,结果是一个警告。
如果使用新的显式隐藏
会员,它抑制这种警告,
记载的事实,得出
版本的目的是作为替代。

When used as a modifier, the new keyword explicitly hides a member inherited from a base class. When you hide an inherited member, the derived version of the member replaces the base-class version. Although you can hide members without the use of the new modifier, the result is a warning. If you use new to explicitly hide a member, it suppresses this warning and documents the fact that the derived version is intended as a replacement.

例如:

class Base
{
 int value;

 virtual bool Foo()
 {
   value++;
 }
}

class Derived : Base
{
 int value;

 override bool Foo()
 {
  value++;
 }

}



我一定要添加修饰符Derived.value申报?什么样的变化?

Do I have to add new modifier to Derived.value declaration? What changes?

推荐答案

由于字段是私人,它不是在派生类中访问。因此,在派生类中声明并没有真正隐藏什么。你不应该添加到该声明。如果你这样做,没有什么变化,除了编译器会警告你使用不正确。如果字段是在派生类访问(例如,它是公共),那么你应该使用来表达你的意图隐藏基成员:

Since the value field is private, it's not accessible in the derived class. Thus, the declaration in the derived class does not really hide anything. You shouldn't add new to the declaration. If you do, nothing changes, except the compiler will warn you about using new incorrectly. If the value field was accessible in the derived class (e.g. it was public), then you should have used new to express your intention to hide the base member:

class A {
    public int field;
}
class B : A {
    public int field; // warning. `B.field` hides `A.field`. 
}

使用将沉默的警告(它没有其他效果):

Using new will silence that warning (it will have no other effect):

class B : A {
    public new int field; // Dear compiler, shut up please.
}

您不能声明的方法既覆盖。它们是相互排斥的。

You can't declare a method as both override and new. They are mutually exclusive.

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

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