A time ago a friend asked the C # New keyword has several uses, although in the daily programming often use this little guy, but it has a few uses in the end really did not pay attention to, now will be summarized from the Internet to write down the information for colleagues to learn.
(1) The new operator is used to create an object and invoke a constructor.
(2) The new modifier is used to hide an inherited member of a base class member.
(3) The new constraint is used to constrain the type of a parameter that might be used as a type parameter in a generic declaration.
New operator
1. For creating objects and calling constructors
Example: class_test MyClass = new Class_test ();
2. Also used to invoke the default constructor for a value type
Example: int myInt = new int ();
MyInt is initialized to 0, which is the default value for type int. The effect of the statement is equivalent to: int myInt = 0;
3. You cannot overload the new operator.
4. If the new operator fails to allocate memory, it throws a OutOfMemoryException exception.
New modifier
Use the new modifier modifier explicitly to hide the members inherited from the base class. To hide an inherited member, declare the member in the derived class with the same name and decorate it with the new modifier.
Take a look at the following class:
以下是引用片段:
1 public class MyClass
2
3 {
4
5 public int x;
6
7 public void Invoke() {}
8
9 }
10