C # Basic----methods and constructors

Source: Internet
Author: User

I have a question! What would you do if I had the same code that needed to be executed in three different places?

Answer one: Copy into three copies and paste them into the three places that need to be executed?

Answer two: Extract this part of the common code in these three places directly call?

If it is me then I must choose the second!!! What about you

The benefits of defined methods

A. Reduce the redundancy of the code. It takes only a few 1 times to be called anywhere.
B. Modification maintenance is convenient, the code in the method as long as 1 change, all calls this method of the place will change.
C. Implementation of covert code.
For callers. There is no need to care about how the method is implemented internally. Just need to care about this method I invoke what can be implemented later

Definition of the method:

Access modifier (static) method return value method name (parameter)

{

The method return value is void so that it does not return data otherwise it needs to return the data using the return keyword

}

  Public classPerson {/// <summary>        ///access modifier: public///void: Indicates no return value///at the same time, the method also has no parameters/// </summary>         Public voidSayhi () {Console.WriteLine ("Hi, hello, everyone! "); }        /// <summary>        ///access modifier: public///return value data type: int///two of the parameters/// </summary>        /// <param name= "one" ></param>        /// <param name= "both" ></param>        /// <returns></returns>         Public intSum (intOneintBoth ) {            intsum =0; Sum= one +both ; returnsum; }    }

Let's look at the invocation of the method

 classProgram {Static voidMain (string[] args) { person person=NewPerson (); //calling a method without parametersPerson .            Sayhi (); //calling a method with a parameter first method requires two parameters then 10 will be assigned to one, 12 will be assigned to two the last method has a return value we define a variable result to accept            intresult = person. Sum (Ten, A); //value of output resultConsole.WriteLine ("The result of the calculation is ="+result);        Console.readkey (); }           }

Finally, let's take a look at the results

Haha above is the simple use of the method

2.0 Constructors

When it comes to constructors, this is actually a special method that requires us to call! But the goods do not need the programmer to call the constructor manually when creating the object is automatically called

 Public classPerson { Public intAge {Get;Set; }  Public stringName {Get;Set; }  Public BOOLGender {Get;Set; } /// <summary>        ///default parameterless (no parameter) constructor/// </summary>         PublicPerson () {}/// <summary>        ///A constructor that has a parameter/// </summary>        /// <param name= "name" ></param>        /// <param name= "age" ></param>        /// <param name= "Sex" ></param>         PublicPerson (stringNameintAgeBOOLsex) {             This. Age =Age ;  This. Name=name;  This. Gender=sex; }    }
  1. The constructor is a 1 special method.                A. Syntax special access modifiers Most of the cases are directly pubic. The constructor does not return a value.                Do not write any void.             The name of the constructor must be the same as the class name in which it resides.  B. Timing of implementation 1).                The construction method cannot be called manually by the programmer.                Person d = new person ();                Creates an object's parentheses. What does it do? The constructor method of the calling object.                2). The execution time of the constructor is automatically called by the New keyword when the object is created.             The creation of the object succeeds only if the new keyword has finished four things.               C. When you create an object, you must call the object's constructor.                2. Constructors can take parameters.             If the constructor takes parameters, you must pass values to the constructor's arguments when creating the object.                           Writes the value of the argument directly in the parentheses of the created object.             3. Constructors can also be overloaded.             That is, you can have multiple constructors, and when you create an object, you can call any of the 1 constructors to complete the creation of the object.             How do you determine which of the 1 constructors to invoke?                         After the creation of the object's parentheses, the number and type of arguments are automatically matched, matching to the 1 constructors to call the 1, the match will not be an error.             4. Function of constructors A. The most important feature of a constructor is the automatic execution of an object while it is being created.                B. When to use a constructor: If there is a segment code, we want to do it automatically while creating the object, then we can put this code in the constructor.                Although this is the case, we recommend that you do not write 1 code that specifically consumes performance and time in the constructor. Because the construction letterAfter the code in the number has been executed. The object is created. If the execution of the constructor takes a lot of time, it can affect the efficiency of creating objects.                Most programmers use constructors to initialize the value of an object's properties.                The constructor parameter writes the type of the object's property and assigns the passed-in parameter to the corresponding property in the method.                               This results in a mandatory effect. The user must assign a value to the property when creating the object. 5. When we do not write arbitrary constructors for the class. At compile time, the compiler automatically generates a constructor for this class of 1 empty method bodies that have no parameters. We're going to call the compiler the constructor for automatic production. So, when we don't write any constructors for the class, we can still invoke the parameterless                          constructor to create the object.             If we write any of the 1 constructors for our class, then the compiler will no longer generate that parameterless constructor for us at compile time.                                             If we are going to call a parameterless constructor, then write 1.  6. Constructors cannot be called manually by the programmer: a. In a normal method, you cannot call a constructor.             However, the normal method can be called in the constructor.                B. Can you call each other between constructors.                Constructors can be called from one another. Syntax: Write 1 colons after the parentheses of the constructor, write 1 This, and then write 1 pairs of parentheses.                The target constructor is matched against the argument in parentheses. Public person (String Name,int age): this () {} public person () {} Order of execution: if a construction letterNumber calls the B constructor.                If a constructor is called when the object is created.                Call the A constructor first.                          Then call the B constructor and execute the B constructor and execute the a constructor.               C. The reason to call the constructor is because we want to reuse the code in the constructor.               When we call the other 1 constructors and give them a string parameter, we can give the 1 data directly.                              You can use the parameters of this constructor when passing parameters.                                              Constructors can not call multiple constructors at the same time, but can have a tune of 1.

C # Basic----methods and constructors

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.