8. Forced type conversion

Source: Internet
Author: User

CLR allows an object to be forcibly converted to its original type or any base type. C # explicitly convert an object to any of its derived types, because such a transformation may fail at runtime. BelowCodeDemonstrate how to convert to base type and derived type:

UsingSystem;

Internal Class Employee

{

//...

}

Public Sealed Class Program

{

Public Static VoidMain ()

{

// No transformation is required, because new returns an employee object, and the object is the base type of the employee.

ObjectO =New Employee();

// Transformation is required because the employee is derived from the object

EmployeeE = (Employee) O;

}

}

Convert using is and:

The is operator checks whether an object is compatible with the specified type and returns a Boolean value, as shown below:

ObjectO =New Employee();

Boolean b1 = (O is Object ); // B1 is true

BooleanB2 = (oIs Employee);// B2 is false

If the object reference is null, the is Operator always returns false. The is operator is usually used as follows:

If (O is employee )

{
EmployeeE = (Employee) O;

//... Use E

}

In this Code, the CLR checks the object type twice. The is operator first checks whether o is compatible with the employee type. If yes, when the if statement content is transformed, CLR checks whether o references an employee again, which has a certain impact on the row performance, because CLR must first determine the actual type of the object referenced by variable O. Then, CLR must traverse the inheritance hierarchy and use each base type to check the specified type of employee. In this regard, C # provides the as operator, which not only simplifies writing, but also improves performance.

EmployeeE = oAs Employee;

If(E! =Null)

{

//... Use E

}

In the preceding code, CLR first checks whether o is compatible with the employee type. If yes, as returns a non-null reference to the same object. If not, null is returned, the Code CLR only verifies the object type once, greatly improving the performance. 


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.