N suggestions for improving C # Program (1-5)

Source: Internet
Author: User
Tags mscorlib

I am free recently. I want to take some time to study java,... (I am not capable of hacking java. I can only say that I am not used to it. It is a bit like a person who is used to Windows operating systems to switch to other systems ). I haven't written C # For a long time, and I saw a copy of "Writing high-quality code: Improving the C # program's 157 suggestions", which is not bad. I can review C #, I rely on C # beginners. you can't lose your housekeeping skills, so you have the idea of writing this series of articles. let's just talk a little more. Let's get started with the question:

Recommendation 1: concatenate strings and values using. ToString () in concatenation. (String str = "str" + 9. ToString ())

string str1 = "str" + 9;string str2 = "str" + 9.ToString();//better

For example, the first line of the above two codes needs to be packed. The second line does not need to be packed. The evidence is as follows:

L_0000: nop     L_0001: ldstr "str"    L_0006: ldc.i4.s 9    L_0008: box int32    L_000d: call string [mscorlib]System.String::Concat(object, object)    L_0012: stloc.0     L_0013: ldstr "str"    L_0018: ldc.i4.s 9    L_001a: stloc.3     L_001b: ldloca.s num    L_001d: call instance string [mscorlib]System.Int32::ToString()    L_0022: call string [mscorlib]System.String::Concat(string, string)    L_0027: stloc.1

The fourth line is the "box" command. it indicates that the packing operation has occurred. although there is only one packing operation. it has no impact on the overall system performance. l_001d calls System. int32.ToString () indicates that the unmanaged code is called through IL and the tracing cannot be continued. but I have code cleanup. I can just clean it.

Suggestion 2: You need to know how to convert the custom type (IP address = (ip) "192.168.0.1 ").

Customize an IP class:

Public class IP: IConvertible, IFormatProvider {IPAddress value; public IP (string ip) {IPAddress. tryParse (ip, out value);} public static implicit operator IP (string ip) {IP iptemp = new IP (ip); return iptemp;} public override string ToString () {return value. toString ();} // omitting some code... public bool ToBoolean (IFormatProvider provider) {throw new InvalidCastException ("IP-to-Boolean conversion is not supported. ");} public string ToString (IFormatProvider provider) {return value. toString ();} // omitting some code... public object GetFormat (Type formatType) {return null ;}}

You can call it as follows:

IP ip = new IP ("192.168.0.1"); ip = (IP)("192.168.0.2"); bool boolIP = ip.ToBoolean(ip); bool boolIP2 = Convert.ToBoolean(ip);

Implicit conversion requires the implementation of the implicit operator (implicit operator) method. If you want to convert to the base element type, you need to implement IConvertible.

Recommendation 3: force transformation and as, is usage

There are two scenarios for forced Transformation:

1. The two types of transformations (for example, implicit conversion and Convert) are completed by the conversion operators ).

2. transition between subclass and parent class.

In the first case, suggestion 2 has already elaborated in detail. What should I do in the second case?

As, is the key word that the C # Language designer (Anders. Hejlsberg) designs for the second case.

Is: determines whether it is an inheritance relationship (return bool)

As: Provides the transformation from a parent class to a subclass. If the transformation fails, no Exception is thrown and only null is returned.

Public static void FatherConvertToSun (Father father) {if (father is sun) {Sun sun = father as Sun; // some code is omitted ....}}

Suggestion 4: Forced transformation between primitive types (convert value types to reference types ).

Value types provide the Tryparse and Parse methods for transformation. The test code is as follows:

Public static void TestTryParse (string item) {double number = 0; Stopwatch sw = Stopwatch. startNew (); for (int I = 0; I <1000; I ++) {if (double. tryParse (item, out number) = true) {number = 0 ;}} long time = sw. elapsedTicks; if (double. tryParse (item, out number) = true) {Console. writeLine (string. format ("TryParse success time: {0}", time);} else {Console. writeLine (string. format ("TryParse failure time: {0}", time ));}}
Public static void TestParse (string item) {Stopwatch sw = Stopwatch. startNew (); double number = 0; for (int I = 0; I <1000; I ++) {try {number = double. parse (item) ;}catch (Exception ex) {number = 0 ;}} long time = sw. elapsedTicks; if (number! = 0) {Console. writeLine (string. format ("Parse success time: {0}", time);} else {Console. writeLine (string. format ("Parse failure time: {0}", time ));}}

The result is as follows:

TyeParse is much more efficient than Parse, especially when the transformation fails. We recommend that you use TryParse transformation between the value type and the reference type.

Suggestion 5: Use environment of the null type.

1. When you read a number from the database, the number can be null (decimal, int) type can be used to prevent the null value to the value type to report an exception.

2. In a distributed system, the server needs to receive and parse the digital data sent from the client. These digital data may also be empty.

Nullable <int> I = null; // declares the Assignment Method 1; int? N = null; // declares the value assignment method 2; int j = n ?? 0; // if n is null, 0 is assigned to j; otherwise, j = I;

A null type has an attribute (HasValue) to determine whether the null type is null.

 

We are here today. We will continue with five suggestions tomorrow.

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.