在C#中,implicit關鍵字可以用來做自定義類型隱式轉換。下面給個例子來說明。
先定義一個Point類,表示一個點:
public class Point
{
public double X { get; set; }
public double Y { get; set; }
}
再在Point類中定義一個靜態方法,用於由字符串隱式轉換為Point類型:
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;
}
}
使用的過程非常簡單,就跟我們平時的隱式轉換一樣:
Point p = "3,4.5";
Console.WriteLine("X:{0}, Y:{1}", p.X, p.Y);
注意,盡量隱式轉換過程中不會出錯,或者能處理異常情況。否則請使用explicit變為強制轉換。