C # custom forced conversions are declared by the keywords in the function, and generally static is used to indicate that they do not depend on type instances.
Example:
Use explicit to declare the display conversion,
1 class LimitedInt 2 { 3 const int MaxValue = 100; 4 const int MinValue = 0; 5 6 public static explicit operator int(LimitedInt li) 7 { 8 return li.TheValue; 9 }10 11 public static explicit operator LimitedInt(int x)12 {13 LimitedInt li = new LimitedInt();14 li.TheValue = x;15 return li;16 }17 18 private int _TheValue = 0;19 public int TheValue20 {21 get { return _TheValue; }22 set23 {24 if (value < MinValue)25 _TheValue = 0;26 else27 _TheValue = value > MaxValue28 ? MaxValue : value;29 }30 }31 }
To assign values, follow these rules:
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 LimitedInt li = (LimitedInt)5; 6 int Five = (int)li; 7 8 Console.WriteLine("li:{0},Five:{1}",li.TheValue,Five); 9 Console.ReadKey();10 }11 }
Press: If you replace the above-mentioned conversion explicit with implicit, it declares implicit conversion (because the program will automatically determine the type of the right value for conversion ), in this case, the display conversion function is not used (or can be used ):
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 LimitedInt li =5; 6 int Five = li; 7 8 Console.WriteLine("li:{0},Five:{1}",li.TheValue,Five); 9 Console.ReadKey();10 }11 }
It can be seen that implicit conversion is easy for us to use, but it is inconvenient to debug in some places. If a type is declared as implicit but other types are not declared, the editor may not be able to detect them, the program running will fail.
C # custom type conversion