C # advanced programming chapter 7th forced conversion of operators and types,

Source: Internet
Author: User

C # advanced programming chapter 7th forced conversion of operators and types,
The basic element of the linearregression operator programming language, which makes our code more concise and clear. However, to solve the problem of different operand types, we introduced the concept of forced conversion. Let's take a look at the content of this chapter.

1. Operators
Let's take a look at some common operators:
<1> conditional Operators
The syntax is as follows:

Condition ? true_Expression : false_Expression

If the Condition is true, true_Expression is executed; otherwise, false_Expression is executed.
<2> checked and unchecked Operators
The syntax is as follows:

Checked {// code block}

You can use the checked operator to check whether the code block being marked has exceeded. If overflow occurs, an OverflowException exception is thrown. If we want to disable the overflow check, use the unchecked operator.
Note: unchecked is the default action. If it is not explicitly marked as checked, all are unchecked by default.
<3> is Operator
The is operator checks whether objects are compatible with specific types. For example, we have two objects, A and B. If expression A is compatible with expression B, expression A is B is true. Otherwise, expression A is false. Compatibility indicates that A and B are of the same type or have A derived relationship between them.
<4> as operator
The as operator is used to perform Explicit conversions of the reference type. If it is compatible with the type to be converted, the conversion is successful. Otherwise, the as operator returns a null value.
<5> sizeof Operator
The sizeof operator can determine the length (in bytes) of the stack's median type ). If you use the sizeof operator for non-basic types, you need to put the code into the unsafe block.
<6> typeof Operator
The typeof operator can return a specific Type of System. Type object. For example, if typeof (string) is returned, it indicates a Type object of the System. String Type.
<7> Null Types and operators
Generally, the null type uses the unary or binary operator. If one of the operands is null, the result is null. If one of the operands is null, the comparison result is false. Therefore, the opposite of a condition that is false is true.
<8> null merge operator (??)
Null merge operator (??) It is convenient to convert an empty type to a non-empty type. Take the null type of int as an example:

Int? A = null; int B = ?? 10; // then B is equal to 10a = 3; B = ?? 10; // B is equal to 3

2. Compare the equality of Objects
Based on the comparison mechanism, we can divide itReference TypeComparison andValue TypeComparison:
<1> compare the equality of reference types
System. Object provides four methods to compare the equality of objects. 

① ReferenceEquals () method
The ReferenceEquals () method is a static method used to test whether two references are the same instance. As a static method, so it cannot be overwritten.
② Virtual Equals () method
The virtual Equals () method, which is a default reference. But because it is a virtual method, we can rewrite it to compare objects by value.
③ Static Equals () method
The static version of Equals () is the same as that of the virtual version. The difference is that the static version has two parameters. One of the two objects can be processed as a null method. However, if two references are compared, it is equivalent to calling the virtual version of Equals (), that is, it is equivalent to rewriting the static Equals () method.
④ Comparison operator (=)
Generally, the reference type uses the comparison operator (before reload is not performed) to compare references (except System. String, because. Net overwrites the comparison operator for String ).
<2> comparison value type equality
When the comparison value type is equal, it is the same as the reference type: ReferenceEquals () is used to compare references, Equals is used to compare values, and basic type = is used to compare values, however, the structure can be compared only when the = Operator is overloaded.
Note: When the ReferenceEquals () method references the value type, it is always false. Because this method is called, the value type needs to be boxed into the object, so it will not get the same reference.
3. Operator Overloading
In many cases, we use operators to represent an expression, which makes our program more concise and easy to understand. On the other hand, the overloading of operators can also improve our development efficiency. Suppose we define a Matrix class Matrix object a, B, c. Suppose we want to express c = a + B. If we use methods to express c = Matrix. add (a, B); I believe that through this example, we should all understand the benefits of operator overloading.
Now let's look at the syntax of Operator Overloading:

// The number of parameters in the parameter list depends on the number of overloaded operators. The public static [return type] operator [overloaded operators] (parameter list) {// processing}

Now that we know the syntax for overloading, let's take a look at it:

// Let's take the vector class as an example. Suppose it has three integer fields x, y, z, and defines the vector addition public static vector operator + (vector lhs, vector rhs) {vector ans = new vector (); ans. x = lhs. x + rhs. x; ans. y = lhs. y + rhs. y; ans. z = lhs. z + rhs. z; return ans ;}

Now we have completed the + operator overloading of the vector class, and now we can directly use + for addition operations. At the same time, the compiler automatically completes the + = overload.
There are two other operators that we cannot directly reload, namely the index operator and the forced conversion operator.
Let's take a look at the overload of the index operator. The syntax is as follows:

[Access attribute] [return type] this [int index] {get {// Add code to return the nth index element} set {// set the nth index element value }}

Let's take the linked list as an example: assume that the basic element type of the linked list is javaslistnode, and the Query (int k) method is used to return references to the k elements and Mod (int k, the listnode node method is used to modify the value of the k element. Therefore, we reload the index operator as follows:

public LinkedListNode this[int index]{get{return Query(index);}set  {Mod(index, value);}}


We have completed the reload of the index operator. Now we can directly use the subscript to access the elements of the set.
Note: The comparison operators in C # Must be overloaded in pairs. For the auto-increment (++) or auto-subtraction (--) operators, the compiler automatically reloads the front ++ in C # As long as the post ++ is overloaded, the same is true for the Self-subtraction operator.
4. Forced type conversion
In many cases, we cannot ensure that all operands are of the same type. This requires forced conversion. However, forced conversions are classified into explicit forced conversions and implicit forced conversions. The conversion between different data types is different. Forced conversion can be divided into five types:
<1> forced conversion of predefined types
In the predefined data type, we only need to remember a rule:
Converting big data to small data requires explicit forced conversion (because this is insecure and data may be lost ), small Data conversion can be explicitly forced or implicitly performed for big data (because it is always secure ).
<2> packing and unpacking
In the process of forced conversion, mutual conversion between value types and reference types is often encountered. However, because the value type is on the stack, the reference type is on the managed stack. This requires packing and unpacking for mutual conversion.
Boxing): Create a temporary reference type "box" on the stack and add the value type to the "box.
Unboxing): The opposite process of packing. Change the original value type in the box.
Note: boxing (converting value type to reference type) can be converted explicitly or implicitly. However, the unboxing must be explicitly forced conversion. In case of binning, you must ensure that the existing value type variables have enough space to store all the bytes of the binning value. Otherwise, an InvalidCastException is thrown.
<3> forced conversion between the base class and the derived class
The compiler provides a forced conversion between the base class and the derived class, but in fact this conversion does not perform any data conversion on the object. It only changes the object reference. Because a base class reference can reference an instance of a derived class. So you can complete the conversion of the derived class to the base class. If the object referenced by the base class is not the object of the derived class, conversion of the base class to the derived class will fail and an exception will be thrown.
We use a piece of code to illustrate (MyBase is the base class, And MyDerived is the derived class of MyBase ):

MyBase B1 = new MyDerived (); // implicitly convert from the derived class to the base class MyBase B2 = new MyBase (); MyDerived D1 = (MyDerived) B1; // MyDerived D2 = (MyDerived) B2 // throw an exception

<4> forced conversion of custom types
Forced conversion of custom types, similar to heavy-load operators. Suppose we want to convert from type A to type B. The syntax for force conversion is as follows:

Public static [Forced type conversion mode] B (A value) {// processing}

The forced conversions are divided into explicit conversions and implicit conversions ).
Here we use an example to understand the forced conversion of custom types. Let's take the previous vector class as an example. Assume that we explicitly convert the vector to double (the square of the modulus of the calculated vector ).

public static explicit double(vector v){return (v.x*v.x + v.y*v.y + v.z*v.z);}

Suppose we have a vector object Test and a double Len.

Len = (double) Test; // now we have completed the call for forced conversion of custom types

Note: In the process of continuous conversion, sometimes the precision may be lost due to the insufficient precision of the data type. However, we can use the Convert. ToUInt16 () method to avoid loss of precision. However, there will be performance loss. This problem can also be avoided by using data types with high precision.
Of course, in the actual process, it is impossible to always convert to the basic data type. The conversion between classes is what we use in daily use. Conversions between classes and classes are similar to conversions between classes and basic data types. The only difference is that the forced conversion between classes hasTwo restrictions:
① If there is an inheritance-derived relationship between classes, the forced conversion between classes cannot be defined (because there is a forced conversion between them)
② Forced type conversion must be defined inside the source or target data type
(This is to prevent the third party from forcibly converting the type into the class)
<5> forced conversion of multiple types
In the conversion process, there is no direct forced conversion method C # the compiler will need to find a conversion method to combine several forced conversions. For example, we have a Foo class that defines the forced conversion of Foo-> int. now we want to convert the Foo object to the double type, then the compiler will convert it like this: foo-> int-> double. However, if you rely on multiple forced conversions, the program's performance will be insufficient. That is to say, if we need to convert the Foo-> double type, we can directly define this type of conversion, and the performance will be more advantageous than multi-conversion.

Appendix:

1. Operators supported by C #

Group

Operator

Primary Operators

(). [] X ++ x -- new typeof sizeof checked unchecked

Unary operator

+ -! ~ ++ X -- x forced conversion of data types

Multiplication/division Operators

*/%

Addition/subtraction Operators

+-

Shift Operator

<>

Relational operators

<> <=> = Is

Comparison Operators

=! =

Bitwise AND operator

&

Bitwise XOR operator

^

Bitwise OR operator

|

Boolean AND operator

&&

Boolean OR operator

|

Conditional Operators

? :

Value assignment operator

= + =-= * =/= % = <<=>>>>> =

2. Support for overloaded operators

Category

Operator

Restrictions

Arithmetic binary Operators

+ */-%

None

Arithmetic unary operator

+-++ --

None

Bitwise binary operator

& | ^ <>

None

Bitwise unary Operators

! ~ True false

Both true and false must be reloaded in pairs.

Comparison Operators

=! ==<=<>

Comparison operators must be reloaded in pairs.

Value assignment operator

+ =-= * =/= % = <<=> =

Do not explicitly reload these operators. The compiler will implicitly reload them.

Index Operators

[]

Cannot directly reload index Operators

Forced conversion operator of Data Type

()

Cannot directly overload the forced conversion Operator


Zookeeper

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.