How to Use operators in C # To overload and convert Operators

Source: Internet
Author: User

How to Use operators in C # To overload and convert Operators
Some programming languages that overload operators allow an instance of the type definition operator to operate on. For example, operators such as (=) and (+) are overloaded for both the string and int types, when the compiler finds that two int-type instances use the + operator, the compiler will generate code that adds the two integers together. When the compiler finds that two string-type instances use the + operator, the compiler will generate code to connect the two strings together. Then how can the compiler know how to do this? How to overload operators? The following C # Code demonstrates how to overload operators in a class: namespace DoNet. seven. consoleApplicationTest {class Program {static void Main (string [] args) {rational r1 = new rational (10); rational r2 = new rational (5); rational r3 = r1 + r2; console. writeLine (r3.Value); Console. readKey () ;}// rational public sealed class rational {private int _ value = 0; public int Value {get {return _ value ;} set {_ value = value ;}} public rationa L (int value) {this. _ value = value;} public rational () {} public static rational operator + (rational num1, rational num2) {rational result = new rational (num1.Value + num2.Value ); return result ;}} run the code. The input result is 15. Use the IL tool to check the code generated by the compiler as follows: 1. First, the CLR specification requires that the operator overload methods must be public and static. In addition, the C # compiler requires that the operator overload method have at least one parameter type, which is the same as the type of the method currently defined. The reason for doing so is that the compiler can find the operator method to be bound within a reasonable period of time. 2. When the compiler of the programming language sees a + operator in the source code, it checks whether there is an operand type that defines a specialname method named op_Addtion, the parameter of this method is compatible with the type of the operand. If such a method exists, the compiler generates code to call it. If such a method does not exist, a compilation error is generated. 3. The following table lists the methods for compiling other operators (the left side is the unary operator and the right side is the binary operator). When designing a type, you should consider the conversion between the operators and other types, this is actually very important. It will be of great benefit to our encoding, just like every type will have a method Tostring (), we define an int type, you can easily use tostring () to convert int to string. Of course, you can also convert it to another type. Like the above rational, it is very convenient to convert an int or double into a rational, and vice versa. // Rational public sealed class rational {private int _ value = 0; public int Value {get {return _ value;} set {_ value = value ;}} public rational (int value) {this. _ value = value;} public rational (double value) {this. _ value = (int) value;} public rational () {} public int ToInt () {return _ value;} public double ToDouble () {return (double) _ value ;} public static rational operator + (rational num1, r Rational num2) {rational result = new rational (num1.Value + num2.Value); return result ;}1. Call these constructors and methods, developers can easily convert int and double objects to rational objects, which brings a lot of convenience to programming. When designing a type, you should carefully consider the conversion constructors and methods supported by the type. 2. We often see code like int I = 10; long j = I; why can the conversion from int type to long type be implemented by the hermit? This involves our conversion operators. Below we also define several conversion operators for rational. Namespace DoNet. seven. consoleApplicationTest {class Program {static void Main (string [] args) {int n = 10; rational r1 = n; double d = (double) r1; Console. writeLine (r1.Value); Console. writeLine (d. toString (); Console. readKey () ;}// rational public sealed class rational {private int _ value = 0; public int Value {get {return _ value ;} set {_ value = value ;}} public rational (int value) {this. _ value = Value;} public rational (double value) {this. _ value = (int) value;} public rational () {} public int ToInt () {return _ value;} public double ToDouble () {return (double) _ value ;} public static rational operator + (rational num1, rational num2) {rational result = new rational (num1.Value + num2.Value); return result;} public static implicit operator rational (int value) {return new rational (value );} Public static implicit operator rational (double value) {return new rational (value);} public static explicit operator int (rational value) {return value. toInt ();} public static explicit operator double (rational value) {return value. toDouble () ;}} outputs 10 and 10. We can switch back and forth between rational, int, and double. Is it very convenient? What does the compiler do for us in this process? In C #, the implicit keyword tells the compiler to call methods in order to generate code, and does not need to display and convert in the source code. On the contrary, the explicit it keyword tells the compiler only when a display transformation is discovered, to call the method. After the implicit or explicit keyword, specify the operator keyword to tell the compiler that the method is a conversion operator. After operator, specify the type of the object to be converted. In parentheses, it specifies the type of conversion from.

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.