Use implicit keywords for implicit conversion of custom types, implicit keywords
In C #, the implicit keyword can be used for implicit conversion of custom types. The following is an example.
First define a Point class to indicate a Point:
public class Point { public double X { get; set; } public double Y { get; set; } }
Then, define a static method in the Point class for implicit conversion from string to Point type:
public class Point { public double X { get; set; } public double Y { get; set; } public static implicit operator Point(string constValue) { var result = new Point(); try { var arPoint = constValue.Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries); result.X = Convert.ToDouble(arPoint[0]); result.Y = Convert.ToDouble(arPoint[1]); } catch { result.X = 0; result.Y = 0; } return result; } }
The process of use is very simple, just like our implicit conversion:
Point p = "3,4.5"; Console.WriteLine("X:{0}, Y:{1}", p.X, p.Y);
Note: Try to avoid errors during implicit conversion or handle exceptions. Otherwise, use explicit to change to forced conversion.