作業會 safe_cast 傳回指定的表達式做為指定的型別。 如果工作不成功,則會擲回 InvalidCastException。
All Runtimes
(這個語言功能沒有適用所有執行階段的備註。)
Syntax
[default]:: safe_cast< type-id >( expression )
Windows 執行階段
使用 safe_cast 來變更指定表達式的類型。 If you expect a variable or parameter to be convertible to a certain type, use safe_cast without a try-catch block to detect programming errors during development. For more information, see Casting (C++/CX).
Syntax
[default]:: safe_cast< type-id >( expression )
Parameters
type-id
The type to convert expression to. 一個控制代碼,可用來參考或值類型、值類型,或參考或值類型的追蹤參考。
expression
一個運算式,可針對用來參考或值類型、值類型,或參考或值類型的追蹤參考之控制代碼進行評估。
Remarks
safe_cast throws InvalidCastException if it can't convert expression to the type specified by type-id. To catch InvalidCastException, specify the /EH (Exception Handling Model) compiler option, and use a try/catch statement.
Requirements
編譯器選項:/ZW
Examples
下列程式代碼範例示範如何搭配 Windows 執行時間使用 safe_cast 。
// safe_cast_ZW.cpp
// compile with: /ZW /EHsc
using namespace default;
using namespace Platform;
interface class I1 {};
interface class I2 {};
interface class I3 {};
ref class X : public I1, public I2 {};
int main(Array<String^>^ args) {
I1^ i1 = ref new X;
I2^ i2 = safe_cast<I2^>(i1); // OK, I1 and I2 have common type: X
// I2^ i3 = static_cast<I2^>(i1); C2440 use safe_cast instead
try {
I3^ i4 = safe_cast<I3^>(i1); // Fails because i1 is not derived from I3.
}
catch(InvalidCastException^ ic) {
wprintf(L"Caught expected exception: %s\n", ic->Message);
}
}
Caught expected exception: InvalidCastException
通用語言執行平台
safe_cast 會變更表達式的類型,併產生可驗證的 MSIL 程式代碼。
Syntax
[cli]:: safe_cast< type-id >( expression )
Parameters
type-id
一個控制代碼,可用來參考或值類型、值類型,或參考或值類型的追蹤參考。
expression 評估為參考或實值型別句柄、實值型別或參考型別追蹤參考的表達式。
Remarks
The expression safe_cast<type-id>(expression) converts the operand expression to an object of type type-id.
編譯程式在 static_cast 接受 的大部分位置接受 safe_cast。 不過, safe_cast 一律會產生可驗證的 MSIL,而 static_cast 可能會產生無法驗證的 MSIL。 如需可驗證程式碼的詳細資訊,請參閱 純和可驗證的程式碼 (C++/CLI) 和 Peverify.exe (PEVerify Tool) 。
如同 static_cast, safe_cast 會叫用使用者定義的轉換。
For more information about casts, see Casting Operators.
safe_cast 不套用 const_cast (投走 const) 。
safe_cast 位於 cli 命名空間中。 如需詳細資訊,請參閱 平臺、預設和 cli 命名空間。
如需 的詳細資訊 safe_cast,請參閱:
Requirements
編譯器選項:/clr
Examples
其中編譯程式不接受 但接受 safe_cast 的static_cast其中一個範例是用於不相關的介面類型之間的轉換。 使用 safe_cast時,編譯程式不會發出轉換錯誤,並在運行時間執行檢查,以查看轉換是否可行。
// safe_cast.cpp
// compile with: /clr
using namespace System;
interface class I1 {};
interface class I2 {};
interface class I3 {};
ref class X : public I1, public I2 {};
int main() {
I1^ i1 = gcnew X;
I2^ i2 = safe_cast<I2^>(i1); // OK, I1 and I2 have common type: X
// I2^ i3 = static_cast<I2^>(i1); C2440 use safe_cast instead
try {
I3^ i4 = safe_cast<I3^>(i1); // fail at runtime, no common type
}
catch(InvalidCastException^) {
Console::WriteLine("Caught expected exception");
}
}
Caught expected exception