RuntimeHelpers.GetObjectValue(Object) 方法

定义

将值类型装箱。

public:
 static System::Object ^ GetObjectValue(System::Object ^ obj);
public static object GetObjectValue (object obj);
public static object? GetObjectValue (object? obj);
static member GetObjectValue : obj -> obj
Public Shared Function GetObjectValue (obj As Object) As Object

参数

obj
Object

要装箱的值类型。

返回

Object

如果 obj 是一个值类,则返回其装箱的副本;否则返回 obj 本身。

示例

下面的示例演示如何使用 方法装箱值 GetObjectValue 类。

using System;
using System.Runtime.CompilerServices;

// Declare a value type.
struct Point2I
{
    public int x;
    public int y;
}

class Program
{

    static void Main(string[] args)
    {
        // Allocate an unboxed Point2I (not on the heap).
        Point2I pnt;
        pnt.x = 0;
        pnt.y = 0;

        // Box the value.  (Put it in the heap.)
        object objPntr = RuntimeHelpers.GetObjectValue(pnt);
    }
}
Imports System.Runtime.CompilerServices

' Declare a value type.
Structure Point2I

    Dim x As Integer
    Dim y As Integer
End Structure

Module Program

    Sub Main(ByVal args() As String)


        ' Allocate an unboxed Point2I (not on the heap).
        Dim pnt As Point2I
        pnt.x = 0
        pnt.y = 0

        ' Box the value.  (Put it in the heap.)
        Dim objPntr As Object = RuntimeHelpers.GetObjectValue(pnt)
    End Sub


End Module

注解

装箱值类型会创建一个对象,并执行指定值类型的字段到新对象的浅表复制。

此方法允许将值类作为对象操作,同时保留值类的别名行为。

返回值取决于值类是可变的还是不可变的:

  • 如果要分配的值是可变值类,则方法返回类的浅表副本,因为值类具有复制语义。

  • 如果要分配的值是不可变的值类,则方法返回对象本身,而不是类的副本。

动态类型语言的编译器可以使用此方法确保装箱的值类型与未装箱的值类型相同。 也就是说,在传递装箱值类型时,会克隆它们,并且它们始终按值传递。 编译器可以调用 GetObjectValue 以将值类型分配给对象或将值类型作为类型对象的参数传递。

编译器使用此方法。

适用于