Usage of the. Net Foundation New keyword

Source: Internet
Author: User
Tags modifiers mscorlib

First, the basic function of new

Generally speaking, the new keyword is used in. NET for the following four occasions.

  1. As an operator for creating objects and calling constructors, the scope is used the most.
  2. Achieve polymorphism.
  3. As a modifier, used to hide inherited class members from a base class member, and in general inheritance, extended base class methods are used much more often.
  4. As a generic parameter constraint, used to constrain a parameter type used as a type parameter in a generic declaration, this also seems to be more useful.
Ii. Basic usage of new
    1. First, the use as a generic parameter constraint.
The definition in MSDN is that the new constraint specifies that any type parameter in a generic class declaration must have a public parameterless constructor. Applies this constraint to a type parameter when a new instance of the type is created by the generic type. One thing to note is that when there are other constraints, the new constraint ratio must be specified last. An example is implemented below: 1 class person<t> where T:new ()
2 {
3 public T GetName ()
4 {
5 return new T ();
6}
7}
8
9 Class Boy
10 {
One private string _name;
12
public string Name
14 {
Get{return _name;}
set {_name = value;}
17}
18
Public Boy ()
20 {
_name = "Feng";
22}
23}
24
Class Program
26 {
static void Main (string[] args)
28 {
person<boy> Mboy = new person<boy> ();
30
Boy a = new boy ();
Console.WriteLine (A.name);
33
Console.WriteLine (Mboy.getname (). Name);
Console.readkey ();
36}
37}

Results print out 2 "Feng"

2. Again, as modifiers and polymorphic usage.

As a modifier, it is primarily used to hide an inherited member from a base class member. If you are implementing a derived class hiding method, the base class method must be defined as virtual, and the base class method is implemented as virtual to guarantee forward extension and backward compatibility. Flexible control with override or new in a derived class, respectively. New and Overdide cannot coexist at the same time, because new is used to create a new member, while hiding a member of the same name in the base class, note that it is not overwritten, and the members that want to access the base class can be accessed through the base modifier. and override is not.

Polymorphism is achieved through new.

    1. For example, a base-class extension is implemented to achieve inherited polymorphism:

      Animal a =new dog ();

      where the Cry () method is implemented as a virtual method, the subclass dog inherits to Animal and overwrite the method, although a is a variable of the parent class animal, but implements the subclass dog method, which is the embodiment of the new implementation polymorphism.

A.cry ();

2. Polymorphism can also be implemented by inheriting interfaces:

Ianimalrun r=new Dog ();//dog implements the Run () method of the interface Ianimalrun

R.run ();

Take a look at the following example to deepen your understanding:


1 class Num
2 {
3 public static int i = 111;
4
5 Public virtual void Showclassinfo ()
6 {
7 Console.WriteLine ("I am the base class hehe");
8}
9 Public virtual void Shownum ()
10 {
One Console.WriteLine ("The number of the base class is {0}", i.ToString ());
12}
13}
14
Class Subnum:num
16 {
New public static int i = 222;
18
//new as modifier: Just hide the base class with the same name method
Public new virtual void Showclassinfo ()
21 {
Console.WriteLine ("I am a sub-class haha");
23}
24
//override is the method of covering the base class.
public override void Shownum ()
27 {
Console.WriteLine ("Number of subclasses is {0}", i.ToString ());
29}
30}
31
Class Program
33 {
The static void Main (string[] args)
35 {
NUM1 num = new num ();//new operator usage
Panax Notoginseng NUM1. Shownum ();
Subnum sbnum = new Subnum ();
39//The following 2 calls are methods of subclasses but the implementation mechanism is different
Sbnum. Shownum ();/results: 111
41
Sbnum. Showclassinfo ();//Result: I am a subclass
43
The//new is used as polymorphic: The following is a typical base-class inheritance-like polymorphism
Num num2 = new Subnum ();//num2 is a variable of the base class, but it points to a reference to such a subnum instance
46
47//When calling a method, the virtual method table is checked at run time to determine which method to invoke
Num2. Showclassinfo ();//Because the method is only hidden, there is no way to override all or call the base class
49
Num2. Shownum ();//method is overridden for all methods that are called subclasses
Wuyi Console.readkey ();
52}
53}

I think the new implementation polymorphism can be put in as an operator not to go, do not know whether you think so.

3. Use as an operator.

As modifiers and constraints may be more understandable, as operators must be an easy topic to understand, because most of the time we use new as an operator to create objects or structs or enumerations, and so on. The new operator returns a reference to the memory address of the managed heap allocated by the system, what is the difference between a new instantiation value type and a reference type, and a simple code.

Class MyClass
2 {
3 private int _id;
4 public MyClass (int id)
5 {
6 _id = ID;
7}
8}
9
Ten struct MYSTRUCT
11 {
The private string _name;
Public MyStruct (string name)
14 {
_name = name;
16}
17}
18
Class Program
20 {
public static void Main ()
22 {
i=0 int;
int j = new int ();
String str = new string (' # ', 10);
26
MyClass MyClass = new MyClass (123);
28
MyStruct mystruct = new MyStruct ("hehe");
30
Console.WriteLine (j);
Console.readkey ();
33}
34}

Let's use the reflector tool to view its IL code as follows:


. method public hidebysig static void Main () cil managed
{
. entrypoint
. maxstack 3
. Locals Init (
[0] Int32 num,//I created here is clearly I anti-compilation is num do not understand, ask everyone to point out
[1] int32 j,//here I changed it myself into J
[2] String str,
[3] class Testnewfunction.myclass MyClass,
[4] valuetype testnewfunction.mystruct mystruct)
L_0000:nop

Manual initialization of I for 0

l_0001:ldc.i4.0
l_0002:stloc.0

Initialize J to 0 with new

The value of l_0003:ldc.i4.0//j is 0
L_0004:stloc.1

Calling newobj initialization string str

L_0005:ldc.i4.s 0x23//' # ' 16 binary
L_0007:ldc.i4.s 10//This 10 should be count
l_0009:newobj instance void [Mscorlib]system.string::.ctor (char, Int32)

L_000e:stloc.2

Call newobj to create the object and invoke the constructor initialization, memory allocated on the managed heap

L_000f:ldc.i4.s Hex of 0x7b//111
l_0011:newobj instance void Testnewfunction.myclass::.ctor (Int32)
L_0016:stloc.3

Load Structure Body

L_0017:LDLOCA.S Struct2
L_0019:ldstr "hehe"

Call constructor initialization, memory allocation on the stack above the thread

L_001e:call instance void Testnewfunction.mystruct::.ctor (String)
L_0023:nop
L_0024:ldloc.1
L_0025:call void [Mscorlib]system.console::writeline (Int32)
L_002a:nop
L_002b:call valuetype [Mscorlib]system.consolekeyinfo [Mscorlib]system.console::readkey ()
L_0030:pop
L_0031:ret
}



I do not know a lot about IL, there are mistakes I hope you can put forward. Through the above analysis, we can draw a conclusion:

    1. When you start a class, call the newobj command to allocate memory for the instance in the managed heap, and then call the constructor to initialize the object.
    2. When a struct is new, its constructor is called directly to complete the initialization.
    3. When new is an int, it is used to initialize its value to 0.

Almost forgot that the new operator is not overloaded, and when allocating memory fails, an OutOfMemoryException exception is thrown.

The above is my use of the new keyword. If there is a mistake, please note.

Source: Chapter Source: http://www.cnblogs.com/xingbinggong/archive/2011/07/05/2098454.html

Usage of the. Net Foundation New keyword

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.