157 recommendations for writing high-quality code to improve C # programs--Recommendation 2: Using the default transformation method

Source: Internet
Author: User

Recommendation 2: Use the default transformation method

In addition to string manipulation, the second common problem programmers encounter is how to correctly transform the type implementation. In the previous recommendation, the transformation from int to string, we used the ToString method of type int. In most cases, you should use the transformation approach provided by the FCL when you need to transform the type provided by the FCL.

These transformation methods include:

Use the type's conversion operator.

Use the types built-in parse, TryParse, or methods such as ToString, ToDouble, and ToDateTime.

Use the methods provided by the Help class.

Use CLR-supported transformations.

These methods are described separately below.

1. Using conversion operators of types

Using a type of conversion operator is actually a method (that is, a function) inside a type. Conversion operators fall into two categories: implicit conversions and explicit conversions (casts). The primitive types generally provide conversion operators, such as:

int 0 ;   float 0 ;   = i;          // an implicit conversion  exists for int to float (single) i = (int) J;     // Float (single) to int exists, and there must be an explicit conversion  

Note that the so-called "primitive type" refers to the data types that the compiler supports directly, that is, the types that map directly to the FCL. Primitive types include sbyte, Byte, short, ushort, int, uint, long, ulong, char, float, double, bool, Decimal, Object, String.

User-defined types can also provide this type of conversion by overloading conversion operators, as shown in the following code:

    classProgram {Static voidMain (string[] args) {IP IP="192.168.0.96"; Console.WriteLine (IP.          ToString ()); }      }           classIp {IPAddress value;  PublicIp (stringIP) {Value=ipaddress.parse (IP); }           Public Static Implicit operatorIp (stringIP) {Ip iptemp=NewIP (IP); returniptemp; }                Public Override stringToString () {returnvalue.          ToString (); }      } 

In the code above:

    1. IP ip = "192.168.0.96";

Provides an implicit conversion of string-to-type IPs. However, unless some initialization values are considered, it is generally not recommended for users to overload conversion operators on their own types. If conversions are required between user-defined types, it is recommended to consider them from an object-oriented perspective because they generally contain some kind of relationship (such as inheritance, implementation, and so on). In this case, you should use the fourth method that will be introduced: CLR-supported transformations. However, we still need to master the types in the FCL, especially the conversion operators between primitive types, so that you can quickly convert between primitive types.

2. Use the type built-in parse, TryParse, or methods such as ToString, ToDouble, ToDateTime, etc.

In the FCL, if a type often needs to be transformed, the type itself will have some transformation methods. For example, the transformation from string to int, because it occurs frequently, so int itself provides the parse and TryParse methods. In general, if you are transitioning to a type, it is recommended that you consult the API documentation for that type first.

3. Methods provided by using the Help class

You can use transformations such as the System.Convert class and the System.bitconverter class to type.

System.Convert provides methods for converting a primitive type to other primitive types, such as ToChar, ToBoolean methods, and so on. It is important to note that System.Convert also supports converting any custom type to any primitive type, as long as the custom type inherits the IConvertible interface. As in the IP class above, if you convert IP to string, you can implement the ToString method of IConvertible In addition to the ToString method of overriding object, as shown in the following code:

    1. class ip : iconvertible  
    2.     //omitted  
    3.     public bool toboolean ( Iformatprovider provider)  
    4.     { 
    5.          throw new invalidcastexception ("Ip-to-Boolean conversion  is not supported. ");  
    6.     }  
    7.  
    8.      public string tostring (Iformatprovider provider)  
    9.      { 
    10.         return value. ToString ();  
    11.     }  
    12.     //omit  

Inheriting the IConvertible interface must implement other transformation methods at the same time, such as the toboolean above, and if this type of transformation is not supported, a InvalidCastException should be thrown instead of a notimplementedexception.

System.bitconverter provides a way to convert between primitive types and byte arrays, which is not discussed here.

4. Using CLR-supported transformations

The transformation that the CLR supports, that is, upstream and downstream transformation. This concept is first proposed in Java, which is actually the conversion between the base class and the subclass, as shown in 1-1.

Implicit conversions are supported when subclasses are transitioning to the base class, such as dog is obviously a animal, and when animal is transformed into dog, it must be an explicit conversion, because animal can also be a cat with the code as follows:

Animal Animal;   New Dog ();   = Dog;       // implicit conversion, because dog is animal   // dog = animal;      // compilation does not  pass Dog = (dog) animal;  //



Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia

157 recommendations for writing high-quality code to improve C # programs--Recommendation 2: Using the default transformation method

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.