[Reprint] usage of the as and is keywords in C,

Source: Internet
Author: User

[Reprint] usage of the as and is keywords in C,
This article mainly introduces the usage of the as and is keywords in C #. For more information, see. Link: http://www.jb51.net/article/80944.htm#comments

In a program, type conversion is common. C # supports basic forced type conversion methods, such:

1 Object obj1 = new NewType(); 2 NewType newValue = (NewType)obj1; 

In this way, this process is not safe during forced conversion, so you need to use the try-catch statement for protection. In this way, the safer code method should be as follows:

Object obj1 = new NewType(); NewType newValue = null; try{   newValue = (NewType)obj1; } catch (Exception err) {   MessageBox.Show(err.Message); } 

However, the above method in C # is outdated and inefficient. The more efficient and fashionable method is to use the as operator, as shown below:

1 Object obj1 = new NewType(); 2 NewTYpe newValue = obj1 as NewType;

Security:

The as operator does not perform too many conversions. If the type of the object to be converted belongs to the conversion target type or to the derived type of the conversion target type, this conversion operation can be successful, in addition, no new object is generated [null is returned when the operation fails ]. Therefore, it is safe to use as for type conversion.

Efficiency:

When the as operator is used for type conversion, first determine the type of the current object and convert the object only when the type meets the requirements, is to use the current object to directly convert, and to protect the conversion success, add try-catch, so, relatively speaking, the as efficiency is high.
It should be noted that, whether it is traditional or as operators for type conversion, before use, you need to determine whether the conversion is successful, as shown below:

1 if(newValue != null) 2 { 3 //Work with the object named “newValue“ 4 } 

Note the following when using the as operator:

1. There is no need to convert the types between types, that is, the compilation error will occur in the following compiling:

1 NewType newValue = new NewType(); 2 NewTYpe1 newValue = newValue as NewTYpe1; 

2. Data of the value type cannot be applied, that is, data of the value type cannot be written as follows (compilation errors may also occur ):

1 Object obj1 = 11; 2 int nValue = obj1 as int; 

For example, you can use the traditional type conversion method:

1 NewTypeOne newTestOne = new NewTypeOne(); 2 NewTypeTwo newTestTwo = (NewTypeTwo)newTestOne; 

To make the above operations complete correctly, add the type conversion operator function to the original type, that is, you need to complete code similar to the following:

1 public calss NewTypeOne 2 {3   public static explicit operator NewTypeTwo( NewTypeOne obj1) 4   { 5   //Convert object into new type 6   } 7 } 

For 2, you can use the is Operator in C # and add the old type conversion operation to complete the conversion safely. To complete the above operation, the correct syntax is as follows:

1 Object obj1 = 11; 2 if(objTest is int ) 3 { 4   int nValue = (int)obj1; 5 } 

A good type conversion method provided in C # is summarized:

Object => known reference type -- completed using the as operator;

Object => known value type -- use the is operator to determine the type, and then use the type forced conversion method for conversion;

Conversions between known reference types -- first, a conversion function must be provided for the corresponding type, and then a conversion is performed using the type-strong conversion method;

Conversions between known value types-it is best to use the static method involved in the Conver class provided by the system.

The following describes how to use the as keyword in C #.

In actual encoding, we sometimes use the as keyword to convert an object to a specified type. Different from the is type, the is keyword is used to check whether the object is compatible with the given type, if it is compatible, true is returned. If it is incompatible, false is returned. The as keyword directly performs type conversion. If the conversion is successful, the converted object is returned. If the conversion is not successful, null is returned instead.

Next we will create a simple use case to illustrate the usage of:

1. Create a window Form application using visual studio2015 as the development environment and name it TransForm.

2. Add a button control to the form for type conversion, add a GroupBox control, and add three RadioButton controls to the control for selection.

3. The detailed code is as follows:

1 private void btn_Get_Checked (object sender, EventArgs e) 2 {3 if (rbtn_object.checked) 4 {5 using (FileStream P_filestream = new FileStream (@ 'd: \ log.txt ', System. IO. fileMode. create) 6 {7 object p_Object = P_filestream as object; 8 if (p_Object! = Null) 9 {10 Message. Box ("converted to Obejct succeeded", "prompt"); 11} 12 else13 {14 Message. Box ("converted to Obejct failed", "prompt! "); 15} 16} 17} 18 if (rbtn_stream.checked) 19 {20 using (FileStream P_filestream = new FileStream (@ 'd: \ log.txt ', System. IO. fileMode. create) 21 {22 obejct p_object = P_filestream; 23 Stream P_Stream = p_objec as Stream; 24 if (P_Stream! = Null) 25 {26 Message. Box ("Stream converted successfully", "prompt"); 27} 28 else29 {30 Message. Box ("Stream converted failed", "prompt! "); 31} 32} 33} 34}

 

 

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.