Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

new modifier in C#

MSDN says:

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.

Example:

class Base
{
 int value;

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

class Derived : Base
{
 int value;

 override bool Foo()
 {
  value++;
 }

}

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...