C # Sharp experience of the six ways to speak

Source: Internet
Author: User
Tags abstract contains functions header inheritance interface win32 domain

The method is also called a member function, which embodies the behavior of the class or object. Methods are also divided into static methods and instance methods. Static methods can manipulate only static fields, and instance methods can manipulate either the instance domain or the static domain-although this is not recommended, it can be useful in some special cases. The method also has the same 5 kinds of accessor modifiers--public,protected,internal,protected internal,private as the domain, and their meanings are as described earlier.

Method parameters

The parameter of the method is a place that deserves special attention. There are four types of parameter passes for the method: by value, pass (by reference), output parameter (by output), array parameter (by array). The pass value parameter requires no additional modifiers, the address parameter needs modifier ref, the output parameter requires a modifier out, and the array parameter requires a modifier params. If you change the value of a parameter during a method call, the parameters of the incoming method do not change after the method call is completed, but instead preserve the value of the original pass in. On the contrary, if the method call procedure changes the value of the parameter, then the parameters of the incoming method will change after the call completes. In fact, from the name we can clearly see the meaning of the two--the value parameter is passed is a copy of the call parameter, and the address parameter is passed the call parameter of the memory addresses, which point to the same storage location inside and outside the method. Look at the example below and its output:

Using System;class test{static void Swap (ref int x, ref int y) {int temp = X;x = Y;y = temp;} static void Swap (int x,int y) {int temp = X;x = Y;y = temp;} static void Main () {int i = 1, j = 2; Swap (ref I, ref J); Console.WriteLine ("I = {0}, J = {1}", I, j); Swap (I,J); Console.WriteLine ("I = {0}, J = {1}", I, J);}}
The program executes output after compiling:

i = 2, j = 1
i = 2, j = 1
We can see clearly that the two commutative functions swap () have different invocation results because of the difference in parameters--the value and the address. Note The method invocation of the address parameter is added with the ref modifier either at the time of declaration or at the time of invocation.

Generally speaking, passing values does not change the value of parameters in some cases is wrong, let's look at the following example:

Using system;class element{public int number=10;} Class test{static void Change (Element s) {s.number=100} static void Main () {element e=new element (); Console.WriteLine (E.number); Change (e); Console.WriteLine (E.number);}
The program executes output after compiling:

10
100
We see that even the value-passing method still alters the object T of the Type element class. But strictly speaking, we are changing the domain of the object T, not the object T itself. Let's look at the following example:

Using system;class element{public int number=10;} Class test{static void Change (element s) {element r=new element (); r.number=100;s=r;} static void Main () {element e=new element (); Console.WriteLine (E.number); Change (e); Console.WriteLine (E.number);}
The program executes output after compiling:

10
10
The value-passing method does not change the object of type element class t! In fact, if we can understand the attributes of the reference type (reference type) in this C # of class, we can see the above two example differences! The reference type itself does not change in the value-passing process (t does not change), but the domain that the reference type contains will change (t. Number changed)! The C # Language reference types are: type Object (including the system-built class type and user-built class type-inherited from Object type), String type, interface type, array type, delegate type. They have the features shown in the two examples above in the call of value.

In the case of values and passes, C # enforces that the parameters are explicitly initialized by the user before they are passed in, or the compiler complains! But if we have a function that doesn't depend on the initial parameter, we just need to get the value of the function when it returns. Often we need this technique in particular when our function returns a value of less than one. The answer is an out-decorated output parameter. However, it is important to remember that there is a difference between the output parameter and the usual function return value: The function return value often exists in the stack, pops up when it is returned, and the output parameter requires the user to make a predetermined storage location, which means that the user needs to declare the variable in advance--of course Look at the following example:

Using System;class test{static void Resolutename (String fullname,out string Firstname,out string lastname) {string[] Stra Rray=fullname. Split (New char[]{'}); firstname=strarray[0];lastname=strarray[1]; public static void Main () {string myname= "Cornfield Lee"; string myfirstname,mylastname; Resolutename (myname,out myfirstname,out mylastname); Console.WriteLine ("My-name: {0}, my last name: {1}", MyFirstName, Mylastname);}
The program executes output after compiling:

My I-Name:cornfield, my last Name:lee
All output parameters must be assigned to the function body, otherwise the compiler will give an error! The out modifier should also be applied to the function declaration and invocation of two places, in addition to acting as the return value of this particular function, the out modifier ref modifier has a very similar place: the address. We can see that C # has completely abandoned the traditional C + + language to give programmers a great degree of freedom, after all, C # is used to develop an efficient next-generation network platform, security-including system security (System structure design) and engineering security (to avoid programmers often make mistakes) is the important consideration of its design, of course, we see C #并没有因为安全性而丧失多少语言的性能, this is the excellence of C #, "Sharp" place!

Array parameters are also one of the places that we often use--passing large numbers of array collection parameters. Let's take a look at the following example:

Using System;class test{static int Sum (params int[] args) {int S=0;foreach (int n in args) {s+=n;} return s;} static void Main () {int[] var=new int[]{1,2,3,4,5}; Console.WriteLine ("The Sum:" +sum (Var)); Console.WriteLine ("The Sum:" +sum (10,20,30,40,50));}
The program executes output after compiling:

The sum:15
The sum:150
As you can see, array parameters can be arrays such as: Var, or can be implicitly converted to an array of parameters such as: 10,20,30,40,50. This provides a high scalability for our programs.

The difference in method parameters of the same name causes the method to appear polymorphic, which is called the overloaded (overloading) method. It should be noted that the compiler binds both method and method calls at compile time. Methods can be overloaded only by the difference of parameters, and other differences, such as return values, do not provide valid overload information for the compiler.

Method inheritance
The first class object-oriented mechanism introduces the Virtual,override,sealed,abstract four modifiers to the C # method to provide different inheritance requirements. A virtual method of a class is a method that can change its implementation in the inheriting class of the class, but this change is limited to changes in the method body, not the method header (method declaration). The virtual method of the quilt class change must be represented by the method header plus override. When a virtual method is invoked, an instance of the class-that is, the object's run-time type (run-time type)-determines which method body is invoked. Let's look at the following example:

Using System;class parent{public void F () {Console.WriteLine ("Parent.f");} public virtual void G () {Console.WriteLine ("Parent.g");} Class Child:parent{new public void F () {Console.WriteLine ("CHILD.F");} public override void G () {Console.WriteLine ("CHILD.G");} Class test{static void Main () {Child b = new Child (); Parent a = B;A.F (); B.f (); A.G (); B.G ();}}
The program executes output after compiling:

Parent.f
Child.f
Child.g
Child.g
We can see that the declaration of the F () method in class child takes the overriding (new) approach to masking the declaration of the Non-virtual Method F () in class parent. The G () method uses the overlay (override) approach to provide the polymorphic mechanism of the method. Note the difference between the rewrite (new) method and the overlay (override) method, which is essentially a compile-time binding, while the override method is Run-time binding. It is worth pointing out that a virtual method cannot be a static method-that is, it is not possible to modify a method with static and virtual at the same time, which is determined by its run-time type discrimination mechanism. Override must be used in conjunction with virtual, and certainly not with static.

So what do we do if we don't want a virtual method to be overwritten in the inheritance system of a class? The answer is sealed override (Seal cover), and we can do this by modifying a virtual method sealed and override at the same time: sealed override public void F (). Note that this must be sealed and override used at the same time, and must be sealed to cover a virtual method, or a virtual method that is overwritten (rather than sealed). It is meaningless and wrong to seal a non-virtual method. Look at the following example:

sealed.cs//csc/t:library sealed.csusing system;class parent{public virtual void F () {Console.WriteLine ("Parent.F");} public virtual void G () {Console.WriteLine ("Parent.g");} Class child:parent{sealed override public void F () {Console.WriteLine ("CHILD.F"), override public void G () {Console.writ Eline ("CHILD.G");} }class grandson:child{override public void G () {Console.WriteLine ("GRANDSON.G");}
Abstract methods are logically similar to virtual methods, but cannot be invoked as virtual methods, but rather as declarations rather than implementations of an interface. The abstract method does not resemble {...} Such a method is implemented, nor is it allowed to do so. Abstract methods can also not be static. Classes that contain abstract methods must be abstract classes and must also be added with the abstract class modifier. Abstract classes, however, do not necessarily contain abstract methods. Subclasses of an abstract class that contains abstract methods must override and implement (directly using override) The method, or combine the abstract override to continue the abstraction, or provide no overrides and implementations. The behavior of the latter two is the same. Look at the following example:

abstract1.cs//csc/t:library abstract1.csusing system;abstract class parent{public abstract void F ();p ublic Abstract V OID G ();} Abstract class Child:parent{public abstract override void F ();} Abstract class grandson:child{public override void F () {Console.WriteLine ("Grandson.f");} public override void G () {Console.WriteLine ("GRANDSON.G");}
Abstract methods can abstract an inherited virtual method, let's look at the following example:

abstract2.cs//csc/t:library abstract2.csusing system;class parent{public virtual void method () {Console.WriteLine () Parent.method ");}} Abstract class Child:parent{public abstract override void Method ();} Abstract class Grandson:child{public override void Method () {Console.WriteLine ("Grandson.method");}
In the final analysis, we grasp the runtime binding and compile-time binding of the basic mechanism, we can see through the methods presented by various forms of overload,virtual,override,sealed,abstract, we can use a good method of this weapon!

External methods

C # introduces an extern modifier to represent an external method. External methods are methods implemented in languages other than C # such as Win32 API functions. The external method cannot be an abstract method, as before. Let's look at one of the following examples:

Using system;using system.runtime.interopservices;class myclass{[dllimport ("user32.dll")]static extern int MessageBoxA (int hWnd, string msg,string caption, int type);p ublic static void Main () {messageboxa (0, "Hello, world!", "Thi S is called from a C # app! ", 0);}}
The program executes output after compiling:

Here we call the Win32 API function int MessageBoxA (int hWnd, string msg,string caption, int type).



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.