C # some confusing concepts (ii) --------- constructor, this keyword, partial classification, enumeration

Source: Internet
Author: User

After analyzing the details of some C # concepts in the previous article, I have gained a lot. In the past, when I was reading a book, a sentence swept away, but now when I re-read it, every sentence found to contain a lot of information. This article will continue to summarize your study notes and give you a deep analysis of some conceptual issues, which will help you understand C. 1. Create a class for the constructor. Copy the code class Program {static void Main (string [] args) as follows) {}}// create a Person class Person {}, copy the code, and generate the code. We use. NET Reflector to decompile the assembly. When the class is compiled, the CLR automatically creates a default constructor for the class. For example, when this object is created, a non-parameter empty method body constructor is generated for this class by default. If we do not explicitly specify the constructor, the CLR will call the default constructor for us. Copy the code class Person {// declare the implemented constructor public Person () {Console. WriteLine ("I'm a superman! ") ;}} Copy the code and decompile the Assembly again. The added constructor overwrites the constructor generated by the C # compiler for this class by default. For example, when a programmer manually adds any type of constructor, the C # compiler does not add the default constructor to the class. Constructor features: ① The access modifier is generally Public ② there is no return value, and the method name is the same as the class name; 2. The role of This keyword ① this keyword indicates the current object, the object currently running in the memory. Let's add the following code: copy the code private int nAge; public int NAge {get {return nAge;} set {nAge = value ;}} // declare the implemented constructor public Person () {this. NAge = 100; Console. writeLine ("I'm a superman! ");} Copy the Code. At this time, we decompile the Assembly and see the following result: the keyword this replaces the current Person object. ② A constructor is followed by the ":" symbol followed by the this keyword. You can call other constructor and add the following code: copy the Code # region object constructor // declare the implemented constructor public Person () {this. NAge = 100; Console. writeLine ("I'm a superman! ");} Public Person (int nAge) {Console. writeLine ("Superman's age {0}", nAge) ;}// use the this keyword to call the second parameter's constructor public Person (int nAge, string strName ): this (1) {Console. writeLine ("My name is {0} Superman, age {1}", strName, nAge) ;}# endregion copy code. Let's create this object to see if the call is successful. Add the following code to the Main function: Person p = new Person (10, ""); run the code. The printed result is as follows: we can analyze the result, when creating an object containing two default parameters, you should first call the constructor of a parameter to initialize the object, and then call the constructor containing two parameters to initialize the object. So is it like this? See the following debugging process: Through the above debugging process, we will find that when the constructor uses the this keyword to call other constructor, the constructor called is called first, before calling a called constructor, you must first execute the called constructor and then execute the directly called constructor. Why is this sequential execution required? Because our default value is 10, we need to print the Superman's age as "10". If we execute the directly called constructor first, it will be overwritten by the called constructor. 3. You can use the partial keyword to declare a class with the same name in the same namespace (the same class name is not allowed by default in the same namespace. For example, if a class with the same name is declared in the same namespace, the compiler reports an error: When we use the Partial keyword, the code can be compiled successfully, for example, add the following code separately: copy the Code partial class Person {private string strAddress; public string StrAddress {get {return strAddress;} set {strAddress = value ;}} private string strNumber; public string StrNumber {get {return strNumber;} set {strNumber = value ;}} public void Run () {}} partial class Person {# region object attribute private int nAge; public int NAge {get {return nAge;} set {nAge = value ;}} private string strName; public string StrName {get {return strName ;}set {strName = value ;}} # endregion # constructor of the region object // declare an implemented constructor public Person () {this. NAge = 100; Console. writeLine ("I'm a superman! ");} Public Person (int nAge) {Console. writeLine ("Superman's age {0}", nAge);} public Person (int nAge, string strName): this (1) {Console. writeLine ("My name is {0} Superman, age {1}", strName, nAge) ;}# endregion public void Sing () {} copy the code and decompile the Assembly again. The following result is displayed: two classes with the same name using the Partial keyword are compiled into the same class. So the characteristics of Partial classification: ① a class with the same name must be used in the same namespace. ② Partial classification is actually a class, C # the compiler will compile them into a class ③ variables defined in one partner class can be accessed in another partner class (because they are a class ). 4. Differences between the Const keyword and the Readonly keyword 1) Add the following code to the Main function: const string strName = ""; Console. writeLine ("My name is {0}", strName); after compilation, I decompile the Assembly and find the following results: the defined constants are not found in the decompilation code, in addition, the place where Const constants are used is replaced by constants. 2) Add the following code for the readonly Keyword: copy the code class cat {readonly string reOnlyName = ""; public cat () {Console. writeLine (reOnlyName) ;}} this Assembly was decompiled after the code was generated. The following result is displayed: The variable modified by readonly is not assigned a value. What is the problem? When we click the cat class constructor, we can see the following results: we find that the variable modified by readonly is assigned a value when it is called. Is the variable modified by readonly immutable? Of course not. We know from The Decompilation results that the variable modified by readonly is assigned a value in the constructor when called, then we can add the following code to modify the default value of readonly In the constructor: copy the code class cat {readonly string reOnlyName = ""; public cat () {this. reOnlyName = "Zi Qiang"; Console. writeLine (reOnlyName) ;}} copy the code and add the following code to the Main () function: cat ct = new cat (); the running result is as follows: the value of the readonly variable is successfully modified in the constructor. Difference between readonly and const: a const constant must be assigned an initial value when declared, so declaring a variable can improve the program running efficiency. When the readonly variable is declared, the initial value can not be assigned, but the initial value must be assigned to the constructor early. That is to say, the const variable determines the constant value during compilation, while readonly determines the value of the variable during runtime. 5. The resolution enumeration level is the same as the class level. You can customize the data type and use ":" After the enumeration name to specify the enumeration type. Read the following code: copy the code // define an enumeration type in one Direction. The enumerated members use "," to separate enum ction: string {east, west, south, north} an error is reported when copying the code. The error message is as follows: we can know that the enumerated data type is value type. Because enumeration is a data type, you can directly declare the access, the following code: copy the code class Program {static void Main (string [] args) {// enumeration is a data type. You can directly declare Direction dr = Direction. east; Console. writeLine (dr); Console. readKey () ;}// defines an enumeration type in one Direction. The enumerated members use "," to separate enum Direction {east, west, south, you can also access the enumeration type to copy the code class Program {static void Main (string [] args) {// The enumerated data type can be directly declared. // Direction dr = Direction. east; Person p = new Person (); // directly call the enumerated Variable p. d Ir = Direction. east; Console. writeLine (p. dir); Console. readKey () ;}} class Person {private string strName; // directly declare the enumerated variable public Direction dir;} copy the code. Each enumerated member corresponds to an integer value, by default, this value increases progressively from 0. You can use forced conversion to obtain the value represented by this enumeration. You can use the following code to access: Direction dr = Direction. east; int I = (int) dr; we can also manually assign values to each enumeration member, representing an integer value, after a value is assigned, the enumerated member represents the assigned value. Run the following code: copy the enum Direction {east = 1, west = 0, south = 2, north = 3} code to convert the string to an enumerated string strDir = "east "; // convert the string to the Enum type of ction d1 = (Direction. parse (typeof (Direction), strDir); // ignore case-sensitive Direction d2 = (Direction) Enum during conversion. parse (typeof (Direction), strDir, true); -------------------------------- split line ------------------------------------ Finally, let's explore a null pointer exception first: copy the code class Dog {private int nAge; public int NAge {get {return nAge;} set {nAge = value ;}} private string strName; public string StrName {get {return strName;} set {strName = value ;}} copy the Code. In the Main () function, we call Dog d = null; d. strName = "trademanager ";

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.