The new keyword in net of c is described in detail

  • 2020-05-19 05:41:14
  • OfStack

1) new operator: used to create objects and call constructors. We're all familiar with it. There's nothing more 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 constrain the type of a parameter that may be used as a type parameter in a generic declaration.

The new keyword is used all the time in our application, so where can the new keyword be used? Consider the following questions:

1. What is the difference between new1 class object and new1 struct object or new1 enum object?

Answer: when new has 1 class, new does 2 things: 1 is to call the newobj command to allocate memory in the managed heap for the instance, and 2 is to call the constructor to initialize the object.

When new1 struct, the new operator is used to call its constructor to complete the initialization of the instance.

2. What else can new do in.NET other than create object instances?

Answer: new keyword: can be used as an operator to create objects and call constructors;

As a modifier, it can be used to hide the inherited members from the base class members and implement the virtual method to hide the base class in the derived class, which cannot coexist with override.

An new constraint specifies that any type parameter in a generic class declaration must have a common argument constructor.

Polymorphism is implemented using the new keyword.

3. Can the new operator be overloaded?

Answer: the new operator cannot be overloaded.

4. What is the role of the new keyword in generics?

Answer: the new operator is used to return a reference to the memory address of the managed heap allocated by the system. If the new failed to allocate memory, an OutOfMemoryException exception will be thrown.

5. What is the difference between new1 inherited method and override?

Answer: new is the hidden base class method, override is the overridden base class method. If you want to access new's hidden base class members, you need to use the base keyword.

6. What is the difference between int i and int i = new int()?

Answer: when new1 int, the new operator is used to initialize its value to 0, enabling the constructor to perform a superior initialization operation.


The name is hidden by inheritance in the following form 1:

The & # 8226; Introduces a constant, specification, property, or type in a class or structure to hide all base class members with the same name.

The & # 8226; Introducing methods in a class or structure to hide properties, fields, and types with the same name in a base class. It also hides all base class methods that have the same signature.

The & # 8226; Introducing an indexer in a class or structure hides all base class indexers with the same name.


Related articles: