RuntimeHelpers.GetObjectValue(Object) 方法

定義

對實值類型進行 Box 動作。

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

要進行 Box 的實值類型。

傳回

如果是值類別,則為 obj Boxed 複本,否則為 obj 本身。

範例

下列範例示範如何使用 方法來 Box a value 類別 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

備註

Boxing 實數值型別會建立 物件,並將指定實值型別字段的淺層複本執行至新的 物件。

這個方法可讓實值類別當做物件操作,同時保留實值類別的別名行為。

傳回值取決於值類別是可變還是不可變:

  • 如果指派的值是可變動的值類別,則方法會傳回類別的淺層複本,因為實值類別具有複製語意。

  • 如果所指派的值是不可變的值類別,此方法會傳回物件本身,而不是類別的複本。

動態類型語言的編譯器可以使用這個方法,確保 Boxed 實值型別的運作方式與 Unboxed 實值型別相同。 也就是說,Boxed 實值型別會在您四處傳遞時複製,而且一律會以值傳遞。 編譯器可以呼叫 GetObjectValue ,將實值型別指派給物件,或將實值型別當做型別物件的參數傳遞。

編譯器會使用這個方法。

適用於