157 recommendations for writing high-quality code to improve C # programs--Recommendation 3: Differentiating between forced transitions and as and is

Source: Internet
Author: User

Recommendation 3: Differential treatment of forced transformation with AS and is

Before elaborating on this recommendation, it is necessary to first identify what a forced transformation is, and what it means to be forced to transform. From a grammatical structure, a code like the following is a forced transformation.

Secondtype = (secondtype) firsttype;

However, a forced transition can mean two different things:

1) Firsttype and Secondtype rely on the conversion operator for each other to complete the transformation between the two types.

2) Firsttype is the base class for Secondtype.

If there is a forced transformation between types, then the relationship between them is either the first, or the second, not both an inherited relationship and a transformational character.

First of all, when the conversion operator is present in Firsttype and Secondtype, the code is as follows:

    classFirsttype { Public stringName {Get;Set; } }           classSecondtype { Public stringName {Get;Set; }  Public Static Explicit operatorSecondtype (Firsttype firsttype) {secondtype Secondtype=NewSecondtype () {Name ="transformation from:"+Firsttype.name}; returnSecondtype; }      } 

In this case, if you want to succeed in transformation, you must use a forced transformation instead of using the as operator.

    New " First Type "  };       = (Secondtype) firsttype;         // Transformation Success       // Secondtype = Firsttype as Secondtype;      //

However, this is not a simple application like the code above, but rather a slightly more complex application. To meet further needs, we need to write a common approach that requires some processing of firsttype or secondtype, and the method should look like this:

    Static void Dowithsometype (object  obj)      {         = (secondtype) obj;      

Notice whether this method is a little familiar with the way it is declared? In fact, if you add a parameter EventArgs, the above method can be registered as a typical CLR event method.

If you run this code, there is a problem: If the passed parameter is a Firsttype object when the method is called, an exception is thrown. You might ask, in the previous section of the code, there is this notation:

    New " First Type "  };      

The code provided by the Dowithsometype method does not look like the following:

    New " First Type "  };       object obj = firsttype;      

In other words, this code compared to the previous code, only a layer of transformation, in fact, obj or firsttype, why the transformation failed? This is because the compiler is not smart enough, or we cheat the compiler. for (Secondtype) obj, the compiler first determines whether there is an inheritance relationship between Secondtype and object. Because in C #, all types are inherited from object, so the above code is definitely not a problem to compile. However, the compiler automatically generates code to check if obj is secondtype at run time, bypassing the conversion operator, so the conversion fails. Therefore, the recommendations here are:

If the types are traced back to a common base class, then the transformation based on this base class (that is, the base class is transformed to the subclass itself) should use as. Transition between subclasses and subclasses, you should provide a conversion operator for a forced transformation.

Note again that the transformation operator is actually a method, and the conversion of the type requires manual write code completion.

In order to write a more robust Dowithsometype method, it should be modified as follows:

    Static void Dowithsometype (object  obj)      {          as  secondtype;           if NULL )          {              //   omit           }      

The as operator never throws an exception if the type does not match (the run-time type of the object being converted is neither the target type being converted, nor its derived type), or the transformed source object is null, then the transformed value is also null. The Dowithsometype method before the transformation will cause the problem of efficiency caused by the exception, and the use of as will be the perfect way to avoid this problem.

Now, let's look at the second case where Firsttype is the base class for Secondtype. In this case, you can either use a forced transformation or use the as operator, as shown in the following code:

    classProgram {Static voidMain (string[] args) {Secondtype Secondtype=NewSecondtype () {Name ="Second Type" }; Firsttype FirstType1=(Firsttype) Secondtype; Firsttype firstType2= Secondtype asFirsttype; }      }           classFirsttype { Public stringName {Get;Set; } }           classSecondtype:firsttype {}

However, even if you can use a forced transformation, from an efficiency standpoint, we recommend that you use the as operator.

Knowing the difference between forced transformation and as, let's look at the is operator. Another version of Dowithsometype, which can be implemented in this way, is shown in the following code:

    Static void Dowithsometype (object  obj)      {          if is secondtype)          {                as Secondtype;               // omitted           }      

This version is obviously not as efficient as the previous version, as the current version has two type detection. However, the as operator has a problem that it cannot manipulate primitive types. If a primitive type algorithm is involved, it needs to be judged by the type before it is transformed to avoid a transformation failure.

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 3: Differentiating between forced transitions and as and is

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.