implicit 關鍵字用於聲明隱式的使用者定義型別轉換運算子。如果可以確保轉換過程不會造成資料丟失,則可使用該關鍵字在使用者定義型別和其他類型之間進行隱式轉換。
樣本
C#
class Digit
{
public Digit(double d) { val = d; }
public double val;
// ...other members
// User-defined conversion from Digit to double
public static implicit operator double(Digit d)
{
return d.val;
}
// User-defined conversion from double to Digit
public static implicit operator Digit(double d)
{
return new Digit(d);
}
}
class Program
{
static void Main(string[] args)
{
Digit dig = new Digit(7);
//This call invokes the implicit "double" operator
double num = dig;
//This call invokes the implicit "Digit" operator
Digit dig2 = 12;
Console.WriteLine("num = {0} dig2 = {1}", num, dig2.val);
Console.ReadLine();
}
}
}
隱式轉換可以通過消除不必要的類型轉換來提高原始碼的可讀性。但是,因為隱式轉換不需要程式員將一種類型顯式強制轉換為另一種類型,所以使用隱式轉換時必須格外小心,以免出現意外結果。一般情況下,隱式轉換運算子應當從不引發異常並且從不丟失資訊,以便可以在程式員不知曉的情況下安全使用它們。如果轉換運算子不能滿足那些條件,則應將其標記為 explicit。有關更多資訊,請參見使用轉換運算子。