safe_cast(C++/CLI 和 C++/CX)

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 工具)。

同样 static_castsafe_cast 调用用户定义的转换。

For more information about casts, see Casting Operators.

safe_cast 不应用 const_cast (投走 const) 。

safe_cast 位于 cli 命名空间中。 有关详细信息,请参阅 平台、默认值和 cli 命名空间

有关详细信息 safe_cast,请参阅:

Requirements

编译器选项:/clr

Examples

编译器不接受但接受转换static_castsafe_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

See also

.NET 和 UWP 的组件扩展