. NET (c #) Three usage of the new Keyword

Source: Internet
Author: User

I went to my company for an interview a few days ago. I had a question like this: I wrote three usage methods of the new keyword in c #. After thinking about it, I only came up with two usage methods. I came back to check msdn, there is really a third usage: it is used to constrain the type of parameters that may be used as type parameters in the generic declaration, which is used only when the generic row is defined in Framework 2.0, your support for c #2.0 is just rough, and no wonder so many brain cells cannot think of this third type!

The three methods are as follows: In C #, The new Keyword can be used as an operator, modifier, or constraint. 1) new OPERATOR: used to create objects and call constructors. Everyone is familiar with this kind of technology and there is nothing to say. 2) new modifier: when used as a modifier, The new Keyword can explicitly hide members inherited from the base class. 3) New constraint: used to restrict the types of parameters that may be used as type parameters in a generic declaration.For the second usage, see the following example: using System; namespace ConsoleApplication1 {public class BaseA {public int x = 1; public void Invoke () {Console. writeLine (x. toString ();} public int TrueValue {get {return x;} set {x = value ;}} public class DerivedB: BaseA {new public int x = 2; new public void Invoke () {Console. writeLine (x. toString ();} new public int TrueValue {get {return x ;}set {x = value ;}} c Lass Test {static void Main (string [] args) {DerivedB B = new DerivedB (); B. invoke (); // call the Invoke method of DerivedB. The output is 2 Console. writeLine (B. x. toString (); // output the member x value of DerivedB: 2 BaseA a = B;. invoke (); // call the Invoke method of BaseA. Output: 1. trueValue = 3; // call the TrueValue attribute of BaseA to modify the value of BaseA member x. writeLine (. x. toString (); // output the value of BaseA member x: 3 Console. writeLine (B. trueValue. toString (); // output the value of member x of DerivedB, which is still: 1 // visible. To access the hidden base class The member variable, attribute, or method of is to shape the subclass as the parent class, and then access hidden member variables, attributes, or methods through the base class. }}} NewAny type parameter in the specified generic class declaration must have a common non-parameter constructor. see the following example: using System; using System. collections. generic; namespace ConsoleApplication2 {public class Employee {private string name; private int id; public Employee () {name = "Temp"; id = 0;} public Employee (string s, int I) {name = s; id = I;} public string Name {get {return name;} set {name = value ;}} public int ID {get {return id;} set {id = value ;}}} Class ItemFactory <T> where T: new () {public T GetNewItem () {return new T () ;}} public class Test {public static void Main () {ItemFactory <Employee> EmployeeFactory = new ItemFactory <Employee> (); // The Compiler checks whether the Employee has a public no-argument constructor. // If not, The Employee must have a public parameterless constructor error occurs. Console. writeLine ("{0} 'id is {1 }. ", EmployeeFactory. getNewItem (). name, EmployeeFactory. getNewItem (). ID) ;}}refer to the New Explanation on MSDN.

New modifier (C # reference)

 

When used as a modifier, The new Keyword can explicitly hide members inherited from the base class. When the inherited member is hidden, the derived version of the member replaces the base class version. Although you can hide a member without using the new modifier, a warning is generated. If new is used to explicitly hide a member, the warning is canceled and the fact that the member is replaced with a derived version is recorded.

To hide an inherited Member, declare the member in the derived class with the same name and use the new modifier to modify the member. For example:

Public class BaseC
{
Public int x;
Public void Invoke (){}
}
Public class DerivedC: BaseC
{
New public void Invoke (){}
}

In this example, DerivedC. Invoke hides BaseC. Invoke. Field x is not affected because it is not hidden by fields with similar names.

Hiding names by inheritance takes one of the following forms:

  • The constant, specified, attribute, or type in the introduced class or structure hides all base class members with the same name.

  • The method in the introduced class or structure hides the attributes, fields, and types of the base class with the same name. It also hides all base class methods with the same signature.

  • The indexer in the introduced class or structure hides all base class indexers with the same name.

It is incorrect to use both new and override for the same member because the meanings of the two modifiers are mutually exclusive. The new modifier creates a new member with the same name and hides the original member. The override modifier extends the implementation of inherited members.

Using the new modifier in a declaration that does not hide inherited members generates a warning.

Example

 

In this example, the base class BaseC and the derived class DerivedC use the same field name x, thus hiding the value of the inherited field. This example demonstrates the usage of the new modifier. It also demonstrates how to use a fully qualified name to access hidden members of the base class.

Public class BaseC
{
Public static int x = 55;
Public static int y = 22;
}

Public class DerivedC: BaseC
{
// Hide field 'x '.
New public static int x = 100;

Static void Main ()
{
// Display the new value of x:
Console. WriteLine (x );

// Display the hidden value of x:
Console. WriteLine (BaseC. x );

// Display the unhidden member y:
Console. WriteLine (y );
}
}
/*
Output:
100
55
22
*/

 

In this example, the nested class hides the class with the same name in the base class. This example demonstrates how to use the new modifier to remove warning messages and how to use a fully qualified name to access hidden class members.

Public class BaseC
{
Public class NestedC
{
Public int x = 200;
Public int y;
}
}

Public class DerivedC: BaseC
{
// Nested type hiding the base type members.
New public class NestedC
{
Public int x = 100;
Public int y;
Public int z;
}

Static void Main ()
{
// Creating an object from the overlapping class:
NestedC c1 = new NestedC ();

// Creating an object from the hidden class:
BaseC. NestedC c2 = new BaseC. NestedC ();

Console. WriteLine (c1.x );
Console. WriteLine (c2.x );
}
}
/*
Output:
100
200
*/

If the new modifier is removed, the program can still be compiled and run, but you will receive the following warning:

The keyword new is required on 'MyDerivedC.x' because it hides inherited member 'MyBaseC.x'.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.