How to take advantage of operator overloading and conversion operators in C #

Source: Internet
Author: User

Original: How to use operator overloading and conversion operators in C #

Operator overloading

Some programming languages allow a type to define an instance of how an operator should manipulate a type, such as a string type and an int type that are overloaded with operators (= =) and (+), and when the compiler discovers two instances of type int using the + operator, the compiler generates a code that adds two integers together.

When the compiler discovers that two instances of string type use the + operator, the compiler generates code that connects two strings together. So how does the compiler know to do that? How do I overload the operator?

The following C # code shows how operator overloading is done in a class:

namespacedonet.seven.consoleapplicationtest{classProgram {Static voidMain (string[] args) {Rational R1=NewRationalTen); Rational R2=NewRational5); Rational R3= R1 +R2; Console.WriteLine (R3.            Value);        Console.readkey (); }    }    //Rational Number     Public Sealed classRational {Private int_value =0;  Public intValue {Get{return_value;} Set{_value =value;} }         PublicRationalintvalue) {             This. _value =value; }         Publicrational () {} Public StaticRationaloperator+(Rational num1,rational num2) {Rational result=NewRational (num1. Value+num2.            Value); returnresult; }    }}

Run code input result is 15

Look at the compiler-generated code with the Il tool as follows:

1. First, the CLR specification requires that the operator overload method be public and static methods. In addition, the C # compiler requires that the operator overload method have at least one parameter of the same type as the currently defined method. The reason why this is done

is for the compiler to be able to find the operator method to bind within a reasonable time.

2, the compiler of the programming language see A + operator appears in the source code, will check whether there is an operand type defines a specialname method named Op_addtion, and the parameter of the method is compatible with the type of the operand,

If such a method exists, the compiler generates the code that calls it. If there is no such a method, a compilation error is generated.

3, for other operators after compiling the corresponding method as shown in the following table (the left is a unary operator, the right is a two-dollar operator)

Conversion operators

When designing a type should take into account the conversion between the other types, this is very important, it will be a great benefit to our coding, like each type will have a method ToString (), we define an int type, it is convenient to use the ToString () method to

int is converted to string and can of course be converted to another type. Just like the rational above, it is convenient to convert an int or double into a rational, and vice versa.

 //Rational Number     Public Sealed classRational {Private int_value =0;  Public intValue {Get{return_value;} Set{_value =value;} }         PublicRationalintvalue) {             This. _value =value; }         PublicRationalDoublevalue) {             This. _value = (int) value; }         Publicrational () {} Public intToInt () {return_value; }         Public Doubletodouble () {return(Double) _value; }         Public StaticRationaloperator+(Rational num1,rational num2) {Rational result=NewRational (num1. Value+num2.            Value); returnresult; }            }

1, call these constructors and methods, developers can easily convert int and double objects into rational objects, which will bring a lot of convenience to the programming work. When designing a type, you should carefully consider the conversion constructors and methods that the type needs to support.

2, int i=10;long j=i; Such code we often see, then the conversion from the int type to the long type can be done by a hermit? This involves our conversion operators, and below we also define several conversion operators for rational.

namespacedonet.seven.consoleapplicationtest{classProgram {Static voidMain (string[] args) {            intn =Ten; Rational R1=N; DoubleD= (Double) R1; Console.WriteLine (R1.            Value);            Console.WriteLine (D.tostring ());        Console.readkey (); }    }    //Rational Number     Public Sealed classRational {Private int_value =0;  Public intValue {Get{return_value;} Set{_value =value;} }         PublicRationalintvalue) {             This. _value =value; }         PublicRationalDoublevalue) {             This. _value = (int) value; }         Publicrational () {} Public intToInt () {return_value; }         Public Doubletodouble () {return(Double) _value; }         Public StaticRationaloperator+(Rational num1,rational num2) {Rational result=NewRational (num1. Value+num2.            Value); returnresult; }         Public Static Implicit operatorRationalintvalue) {            return NewRational (value); }         Public Static Implicit operatorRationalDoublevalue) {            return NewRational (value); }         Public Static Explicit operator int(rational value) {returnvalue.        ToInt (); }         Public Static Explicit operator Double(rational value) {returnvalue.        ToDouble (); }    }}

The result of the output is 10, 10. We can switch back and forth between rational, int, and double, is it very convenient, in this process, what does the compiler do for us?

In C #, the implicit keyword tells the compiler to invoke a method in order to generate code and does not need to display the conversion in the source code, instead, the explicit keyword tells the compiler to call the method only if the display transformation is discovered.

After the implicit or explicit keyword, to specify the operator keyword tells the compiler that the method is a conversion operator. After operator, specify what type the object will be converted to. Within parentheses, specifies what type to convert from.

The C # compiler detects transformations in the code and generates IL code internally to invoke the transformation operator method defined by the rational type, and if you look at it with the anti-compiler, the conversion operator method generates the following code:

Conclusion

Whether the operator overload or the conversion operator is designed for the design type to be convenient for our coding, let's look at the definition of the decimal type in C #.

How to take advantage of operator overloading and conversion operators in C #

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.