Implicit and explicit conversions are often encountered during type conversion. How can we define implicit and explicit conversions for custom types? Let's look at a piece of code.
Public class rational {int32 private _ inner_int = 0; public rational () {} public rational (int32 num) {This. _ inner_int = num;} public int32 toint32 () {return this. _ inner_int;} // implicitly constructs and returns a rational from an int32 public static implicit operator rational (int32 num) {return New Rational (Num );} // explicitly returns an int32 from a rational public static explicit operator int32 (rational R) {return r. toint32 ();} public override string tostring () {// return base. tostring (); string S = string. format ("{0}", this. _ inner_int); Return s ;}}
Test code
Class program {static void main (string [] ARGs) {rational R1 = 10; console. writeline (R1); int32 I = R1; console. writeline (I); console. readline ();}}
An error will be reported during editing. See
From the prompt, we can see that the explicit conversion is missing when int32 I = R1. Now we add the display conversion. The modified code and output result are as follows:
The output result is 10.
Why? The reason is that when rational is converted to int32, explicit expression must be specified. If you replace explicit with implicit (implicit), the original code runs normally.
Modified rational
Public class rational {int32 private _ inner_int = 0; public rational () {} public rational (int32 num) {This. _ inner_int = num;} public int32 toint32 () {return this. _ inner_int;} // implicitly constructs and returns a rational from an int32 public static implicit operator rational (int32 num) {return New Rational (Num );} // explicitly returns an int32 from a rational public static <span style = "color: # ff0000;"> implicit </span> operator int32 (rational R) {return r. toint32 ();} public override string tostring () {// return base. tostring (); string S = string. format ("{0}", this. _ inner_int); Return s ;}}
Test code and output result
It can be seen that explicit and implicit affect explicit and implicit conversions of types.
In fact, an implicit conversion has been executed on rational R1 = 10. The conversion code is as follows:
// Implicitly constructs and returns a rational from an int32 public static implicit operator rational (int32 num) {return New Rational (Num );}
If you replace implicit with explicit, rational R1 = 10 will also report an error (you can test it yourself ).
Reprinted please indicate the source: http://blog.csdn.net/xxdddail/article/details/38057563
C # custom implicit and explicit Conversions