跳轉到內容

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

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

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

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

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

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

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

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

關鍵字

[編輯 | 編輯原始碼]

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

explicit關鍵字用於建立僅透過指定顯式型別轉換才能使用的型別轉換運算子。

此結構有助於軟體開發人員編寫更易讀的程式碼。具有顯式轉換名稱可以清楚地表明正在進行轉換。

class Something 
{
  public static explicit operator Something(string s)
  {
     // Convert the string to Something
  }
}

string x = "hello";

// Implicit conversion (string to Something) generates a compile time error
Something s = x;

// This statement is correct (explicit type name conversion)
Something s = (Something) x;



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
華夏公益教科書