跳轉至內容

C# 程式設計/關鍵字/隱式

來自華夏公益教科書,開放的書籍,開放的世界

當值隱式轉換時,執行時不需要開發人員在程式碼中進行任何轉換才能將值轉換為其新的型別。

以下是一個示例,其中開發人員在顯式轉換。

// Example of explicit casting.
float fNumber = 100.00f;
int iNumber = (int) fNumber;

開發人員已告訴執行時,“我知道我在做什麼,強制進行此轉換。”

隱式轉換意味著執行時不需要任何提示即可進行轉換。以下是一個示例。

// Example of implicit casting.
byte bNumber = 10;
int iNumber = bNumber;

請注意,開發人員不需要進行任何轉換。隱式轉換的特殊之處在於,型別轉換到的上下文是完全無損的,即轉換到此型別不會丟失任何資訊。因此,它可以毫無顧慮地轉換回來。

關鍵字

[編輯 | 編輯原始碼]

關鍵字 implicit 用於型別定義如何隱式轉換。它用於定義哪些型別可以在沒有顯式轉換的情況下進行轉換。

例如,讓我們拿一個 Fraction 類,它將儲存一個分子(除法符號上方的數字)和一個分母(除法符號下方的數字)。我們將新增一個屬性,以便該值可以轉換為 float

public class Fraction
{
     private int nominator;
     private int denominator;

     public Fraction(int nominator1, int denominator1)
     {
          nominator = nominator1;
          denominator = denominator1;
     }

     public float Value { get { return (float)_nominator/(float)_denominator; } }

     public static implicit operator float(Fraction f)
     {
          return f.Value;
     }

     public override string ToString()
     {
          return _nominator + "/" + _denominator;
     }
}

public class Program
{
    [STAThread]
     public static void Main(string[] args)
     {
          Fraction fractionClass = new Fraction(1, 2);
          float number = fractionClass;

          Console.WriteLine("{0} = {1}", fractionClass, number);
     }
}

重申一下,它隱式轉換到的值必須以原始類可以轉換回的形式儲存資料。如果這不可能,並且範圍被縮小(例如將 double 轉換為 int),則使用顯式運算子。



C# 關鍵字
abstract as base bool break
byte case catch char checked
class const continue decimal default
delegate do double else enum
event explicit extern false finally
fixed float for foreach goto
if implicit in int interface
internal is lock long namespace
new null object operator out
override params private protected public
readonly ref return sbyte sealed
short sizeof stackalloc static string
struct switch this throw true
try typeof uint ulong unchecked
unsafe ushort using var virtual
void volatile while
特殊 C# 識別符號(上下文關鍵字)
add alias async await dynamic
get global nameof partial remove
set value when where yield
上下文關鍵字(用於查詢)
ascending by descending equals from
group in into join let
on orderby select where
華夏公益教科書