Unsafe.As 方法

定义

重载

As<T>(Object)

将给定对象强制转换为指定类型。

As<TFrom,TTo>(TFrom)

将给定的托管指针重新解释为指向 类型的 TTo值的新托管指针。

As<T>(Object)

Source:
Unsafe.cs
Source:
Unsafe.cs
Source:
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

要强制转换的对象。

返回

T

原始对象,强制转换为给定类型。

注解

此 API 用于将对象强制转换为给定类型,从而抑制运行时的正常类型安全检查。 调用方有责任确保转换是合法的。 不会 InvalidCastException 引发。

只有在典型的“安全”强制转换操作(T)o成功时,才明确定义 的行为Unsafe.As<T>(o)。 不支持使用此 API 来规避本来会失败的强制转换,并可能导致运行时不稳定。

为了帮助强制实施正确的用法,开发人员可以考虑在其代码中使用标准强制转换或仅调试断言,如以下示例所示。

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)

Source:
Unsafe.cs
Source:
Unsafe.cs
Source:
Unsafe.cs

将给定的托管指针重新解释为指向 类型的 TTo值的新托管指针。

public:
generic <typename TFrom, typename TTo>
 static TTo % As(TFrom % source);
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

指向 类型的 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}");

此程序的输出取决于当前计算机的结束度。 在 big-endian 体系结构中,此代码输出 0x1234。 在 little-endian 体系结构中,此代码输出 0x5678

将托管指针从较窄的类型转换为较宽的类型时,调用方必须确保取消引用指针不会产生越界访问。 调用方还负责确保生成的指针与引用的类型正确对齐。 有关对齐假设的详细信息,请参阅 ECMA-335,第 I.12.6.2 (“Alignment”) 。

适用于