Прочетете на английски Редактиране

Споделяне чрез


RuntimeHelpers.GetObjectValue(Object) Method

Definition

Boxes a value type.

C#
public static object GetObjectValue(object obj);
C#
public static object? GetObjectValue(object? obj);

Parameters

obj
Object

The value type to be boxed.

Returns

A boxed copy of obj if it is a value class; otherwise, obj itself.

Examples

The following example demonstrates how to box a value class by using the GetObjectValue method.

C#
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);
    }
}

Remarks

Boxing a value type creates an object and performs a shallow copy of the fields of the specified value type into the new object.

This method allows a value class to be manipulated as an object while it retains the aliasing behavior of a value class.

The return value depends on whether the value class is mutable or immutable:

  • If the value being assigned is a mutable value class, the method returns a shallow copy of the class, because value classes have copy semantics.

  • If the value being assigned is an immutable value class, the method returns the object itself, instead of a copy of the class.

Compilers of dynamically typed languages can use this method to make sure that boxed value types work identically to unboxed value types. That is, boxed value types get cloned when you pass them around, and they are always passed by value. The compiler can call GetObjectValue to assign a value type to an object or to pass a value type as a parameter of a type object.

This method is used by compilers.

Applies to

Продукт Версии
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0