Unsafe.As 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
多載
| 名稱 | Description |
|---|---|
| As<T>(Object) |
將給定物件投射到指定的類型。 |
| As<TFrom,TTo>(TFrom) |
將給定的受管理指標重新詮釋為一個新的受管理指標,指向一個型別 |
As<T>(Object)
- 來源:
- Unsafe.cs
- 來源:
- Unsafe.cs
- 來源:
- Unsafe.cs
- 來源:
- Unsafe.cs
- 來源:
- Unsafe.cs
將給定物件投射到指定的類型。
public:
generic <typename T>
where T : class static T As(System::Object ^ o);
public static T? As<T>(object? o) where T : class;
public static T As<T>(object o) where T : class;
static member As : obj -> 'T (requires 'T : null)
Public Shared Function As(Of T As Class) (o As Object) As T
類型參數
- T
物件將被鑄造成的類型。
參數
- o
- Object
要施法的物品。
傳回
原始物件,鑄造成指定類型。
備註
此 API 用於將物件鑄造成指定型別,抑制執行時的正常型別安全檢查。 來電者有責任確保演員陣容合法。 不會 InvalidCastException 被丟棄。
只有當典型的「安全」鑄造操作(T)o成功時,才會明確定義 的Unsafe.As<T>(o)行為。 使用此 API 來繞過本可能失敗的投射是不被支援的,且可能導致執行時不穩定。
為了協助強制正確使用,開發者可考慮在程式碼中使用標準 cast 或僅除錯的斷言,如下範例所示。
void ReinterpretCastAndUse_Sample1(object o)
{
// Assume that we know through some other means that 'o' is a string,
// and we want our library's debug builds to verify this.
// One way to do this is through a standard-style cast.
// A standard-style cast will throw InvalidCastException at runtime if the cast fails.
// n.b. Casts of null objects to reference types will succeed.
#if DEBUG
string s = (string)o;
#else
string s = Unsafe.As<string>(o);
#endif
DoSomethingWith(s);
}
void ReinterpretCastAndUse_Sample2(object o)
{
// Another way to check this is through a debug-only assert.
// Failed assertions will trigger attached debuggers or terminate the application immediately.
// Calls to Debug.Assert are removed from release builds.
Debug.Assert(o is null or string, "Unsafe.As call below is illegal!");
string s = Unsafe.As<string>(o);
DoSomethingWith(s);
}
適用於
As<TFrom,TTo>(TFrom)
- 來源:
- Unsafe.cs
- 來源:
- Unsafe.cs
- 來源:
- Unsafe.cs
- 來源:
- Unsafe.cs
- 來源:
- Unsafe.cs
將給定的受管理指標重新詮釋為一個新的受管理指標,指向一個型別 TTo為 的值。
public:
generic <typename TFrom, typename TTo>
static TTo % As(TFrom % source);
public static ref TTo As<TFrom,TTo>(ref TFrom source) where TFrom : allows ref struct where TTo : allows ref struct;
public static ref TTo As<TFrom,TTo>(ref TFrom source);
static member As : 'From -> 'o
Public Shared Function As(Of TFrom, TTo) (ByRef source As TFrom) As TTo
類型參數
- TFrom
這種可管理的指標需要重新詮釋。
- TTo
管理指標的期望類型。
參數
- source
- TFrom
管理指標重新詮釋。
傳回
一個管理指標指向型別 TTo為 的值。
備註
此 API 在概念上與 C++ reinterpret_cast<>相似。 來電者有責任確保演員陣容合法。 不會執行執行時檢查。
只有受管理指標會被重新詮釋。 參考值本身保持不變。 請考慮下列範例。
int[] intArray = new int[] { 0x1234_5678 }; // a 1-element array
ref int refToInt32 = ref intArray[0]; // managed pointer to first Int32 in array
ref short refToInt16 = ref Unsafe.As<int, short>(ref refToInt32); // reinterpret as managed pointer to Int16
Console.WriteLine($"0x{refToInt16:x4}");
此程式的輸出取決於當前機器的字序。 在大端架構中,此程式碼輸出 0x1234。 在小端架構中,此程式碼輸出 0x5678。
當將受管理指標從較窄類型鑄造到較寬類型時,呼叫者必須確保取消參照指標不會產生越界存取。 呼叫者同時負責確保所得指標與參考型別正確對齊。 欲了解更多關於對齊假設的資訊,請參閱 ECMA-335,第I.12.6.2節(「對齊」)。