Fat rabbit Reading Notes Objective C # (2nd) Chapter 1

Source: Internet
Author: User

Tive C # (version 2nd)The Chinese name is:C # efficient programming to improve C #50 effective methods of code (version 2nd)

The Chinese name of this book is very painful, and the titles of other article series are all Article tive XXX, which can be found by inputting Article tive in the online store, but this book cannot be found, the Chinese name was later known by chanceC # efficient programming to improve C #50 effective methods of codeIt really hurts a lot.

Chapter 1 C # language habits

Entry 1 uses attributes instead of accessible data members
Entry 2 uses readonly instead of Const)
Entry 3 The is or as operator is recommended instead of forced type conversion.
Entry 4 uses the conditional feature instead of # If condition Compilation
Entry 5 provides the tostring () method for the type.
Entry 6 understands the relationship between several equality judgments
Entry 7 understands the trap of gethashcode ()
Item 8 the query syntax is recommended instead of the loop
Entry 9 avoid using conversion operators in Apis
Entry 10: use optional parameters to reduce the number of method Overloading
Item 11 advantages of short methods
Summary

Entry 1 uses attributes instead of accessible data members

Programmers know this concept. The reason is that attributes of programming have become a habit. If you write code without attributes, it will be despised, attributes can be better encapsulated, and permission access control can be better implemented. However, although the attributes and data members are completely compatible at the source code level, they are quite different at the binary level. This means that if you change a public data member to an equivalent public attribute, you must re-compile all code that uses the public data member, otherwise, an exception is thrown during running.

As shown below, if the customer class is referenced by other programs or classesVariableChangeAttributeYou must re-compile all the code that references the customer class. Otherwise, an error will occur during the runtime. Although we don't seem to have any difference, changing the public variable to the attribute breaks the binary compatibility, this makes it very difficult to update a single assembly. It doesn't have much practical significance to understand this, but it makes us more confident in using attributes.

Public Class Customer {// <summary> // The Public variable is declared here. // </Summary> Public string name ;} public Class Customer {/// <summary> /// the public attribute is declared here. // </Summary> Public string name {Get; Set ;}}
Entry 2 uses readonly instead of Const)

C # There are two types of constants:Constant during compilationAndRuntime frequency. The two have completely different behaviors. improper use may cause serious consequences, and users are at a loss.

The const keyword declaration is used for constants during compilation, and readonly keyword declaration is used for runtime.
The compile-time constants can be declared in the class or method. The runtime constant can only be declared in the class and cannot be declared in the method.

/// <Summary> /// Number of compilation times /// </Summary> Public const int constage = 23; /// <summary> /// runtime volume /// </Summary> Public static readonly int readonlyage = 23;

 The differences between constants during compilation and runtime often occur in different ways of accessing them. The value of the constant during compilation is replaced in the target code.. For example

if (ReadonlyAge == ConstAge) 

It will be compiled into the same Il as the following code

if (ReadonlyAge == 23)

The consequence of this difference is that when a constant defined by the const keyword is referenced during compilation, if the Assembly that defines the constant changes, and the referenced assembly is not re-compiled, in this way, an inexplicable error occurs. For example, the Assembly utility defines a const field and a readonly field:

Namespace utility {public class democlass {/// <summary> /// the compilation frequency. /// </Summary> Public const int constnum = 3; public static readonly int readonlynum = 3 ;}}

Utility assembly is referenced in assembly consoleapplication1 and is called as follows:

static void Main(string[] args){    Console.WriteLine("ConstNum:" + Utility.DemoClass.ConstNum);    Console.WriteLine("ReadonlyNum:" + Utility.DemoClass.ReadonlyNum);          }

Output result:

ConstNum:3ReadonlyNum:3

Modify the utility Assembly as follows:

Namespace utility {public class democlass {/// <summary> /// the compilation frequency. /// </Summary> Public const int constnum = 10; public static readonly int readonlynum = 10 ;}}

Update consoity Assembly reference in consoleapplication1, and did not re-compile consoleapplication1 assembly. The output is as follows:

ConstNum:3ReadonlyNum:10

The output is not as expected

ConstNum:10ReadonlyNum:10

Compilation frequencyIt can only be defined as a basic type: integer, floating point number, enumeration, and stringOther types cannot be defined as constant const even if they are value types. For example:

/// <Summary> /// this definition does not work. Compilation fails. /// </Summary> Public const datetime now = datetime. now;

Summary: unless the data cannot be changed, do not define the const constant of the Public type. If necessary, define them as private type. To define constants, use static readonly instead, first, readonly supports more and more flexible types. Second, const has no difference with static readonly in terms of performance advantages.

Entry 3 The is or as operator is recommended instead of forced type conversion.

If you need to use type conversion, try to use the as operator. Forced type conversion may have a negative impact on the intention, because as is safer and more efficient than forced type conversion, if you use as for conversion, no exception is thrown. If the conversion fails, null is returned.

Entry 4 uses the conditional feature instead of # If condition Compilation

It seems that it is of little practical use. After all, there are not many if operations in practice. It is not necessary to spend that energy studying conditional.

Entry 5 provides the tostring () method for the type.

Similar to above, it seems that the actual use is not great. To implement the tostring () method for each object class, it is a bit superfluous to observe the attribute information of each class () in addition, you need to check whether all attributes have been added. If you modify the attributes, the more code, the higher the error probability, unless it hurts, you will not be able to do this thankless task.

Entry 6 understands the relationship between several equality judgments

It is of little practical use. It mainly introduces several equal judgment methods. More details are used to introduce the equals method and it is recommended to rewrite the equals method of all value types, I am not sure. It may be that our understanding level is too low. How many opportunities do we have to actually define value types?

Entry 7 understands the trap of gethashcode ()

What about this? Basically, I have used gethashcode () to do practical and meaningful things (not counted in the unconscious usage ), so the traps and the like do not exist for me. Haha, skip this step and study them later.

Item 8 the query syntax is recommended instead of the loop

This is mainly because we recommend that you replace the complicated for, foreach, and while loops with the LINQ syntax in daily development (although sometimes the for loop is not complex, it is obviously more concise to use it ), the advantage is that the Code is more concise, can clearly express your intention, readability, ease of use is greatly higher, and it is easier to use parallel computing to take full advantage of the advantages of multi-core CPU, simply add. asparallel, parallel programming is so simple

Entry 9 avoid using conversion operators in Apis

In fact, there are few applications that use conversion operators anywhere, not to mention using them in APIs. At least I have met some of them and skipped them.

Entry 10: use optional parameters to reduce the number of method Overloading

. Net4.0 began to support the default parameter values. The default value of the application parameter changes the parameter to an optional parameter, and we can finally free it from endless overloading. Of course, the optional parameters are not omnipotent.Entry 1Similarly, after the default parameter value is modified, the referenced assembly and code must be re-compiled. However, I still need to applaud the optional parameter for the inconvenience.
In the past, we had to implement the following calls:

static void Main(string[] args){    SetUserName("LazyRabbit");    SetUserName("LazyRabbit", "cnblogs");}

You need to write the following two reloads for implementation.

public static void SetUserName(string last){}public static void SetUserName(string last, string first){}

Let's take a look at the charm of the optional parameters. We only need to define a method to achieve the same effect.

public static void SetUserName(string last, string first = "LazyRabbit"){}
Item 11 advantages of short methods

We usually code many people know that we should try not to make a method code too much, too much code will cause poor readability, and it also means that a single method has more responsibilities, not conducive to expansion, reuse and modification, this article does not discuss these points, but mainly introduces the optimization of JIT in the compilation stage ,. net runtime will call the JIT compiler to translate the Il generated by the C # compiler into machine code, this process is spread throughout the application lifecycle, at the beginning, JIT does not fully compile all the Il, and CLR will perform JIT compilation one by one based on the granularity of the function, which greatly reduces the code started by the program, methods that are not called are not compiled by JIT at all, therefore, splitting those not very important logical branches into more small branches has better performance than putting all the logic together to form large-scale complex functions. The short method enables JIT to better share compiled code and improve the efficiency of running the program. The following code: When the demomethod method is called for the first time,If-else is compiled by JIT.In fact, only one branch needs to be compiled.

public static void DemoMethod(bool condition){    if (condition)    {    //do Method1 thing    }    else    {    //do Method2 thing    }}

If it is changed to the following form, only one of Method1 () or method2 () will be compiled when the demomethod method is called for the first time, which is obviously more efficient.

public static void DemoMethod(bool condition){    if (condition)    {    Method1();    }    else    {    Method2();    }}public static void Method1(){    //do Method1 thing}public static void Method2(){    //do Method2 thing}

The above code is somewhat far-fetched, but how much improvement can actually be achieved? This improvement may be minimal, but it is certain that the more complicated the method, the more improvements will be, at the same time, the smaller the method, the more easy it is for JIT to select registers and store local variables in registers rather than stacks. Smaller functions mean fewer local variables, it is more convenient for JIT to optimize registers.

So far, Chapter 1C # language habitsAfter reading this article, I will record it here for my memo and review. Some of my views have been known before, and I have learned some understanding and understanding through reading, if you feel useful, you should study it carefully. If you feel that the practical value is not high, you can also read it. When you know about it, you may use it someday.

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.