Boxing, what are your preferences and which, in your opinion, is faster?

In short, I think boxing is a nuisance. Let's look at some alternatives ...

public class Box<T> 
    where T : struct
{
    public T Value { get; set; }

    public static implicit operator T(Box<T> box)
    {
        return box.Value;
    }
}

System.Int32 comes from the abstract System.ValueType class, which comes from the System.Object class. You cannot get from System.ValueType in C #, but I would suggest that the struct keyword does just that, and the CLI recognizes these types of type definitions as having pass-by-value semantics. Anyway, when a struct is assigned an object type, boxing occurs. I don’t want to get into boxing as such, instead I want to get straight to it.

I looked at the part of the IL generated by the C # compiler.

object obj = 1;

.locals init ([0] object obj)
L_0000: nop 
L_0001: ldc.i4.1 
L_0002: box int32 // Convert a value type (of the type specified in valTypeToken) to a true object reference. 
L_0007: stloc.0 

Found this on MSDN ...

A value type has two separate representations within a common language infrastructure (CLI):

  • "raw", , .

  • A 'boxed' form, ( ) , .

, , ...

var box = obj as Box<int>;
if (box != null)
{
    Console.WriteLine(box.Value);
}

System.Object, , unbox box ValueType ? , , - ?

- - ? , , - , , . -. , ValueType ( 8 ), "ReinterpretCast".

[StructLayout(LayoutKind.Explicit)]
public struct ReinterpretCast
{
    [FieldOffset(0)] sbyte @sbyte;
    [FieldOffset(0)] byte @byte;
    [FieldOffset(0)] short @ushort;
    [FieldOffset(0)] ushort @short;
    [FieldOffset(0)] int @int;
    [FieldOffset(0)] uint @uint;
    [FieldOffset(0)] long @long;
    [FieldOffset(0)] ulong @ulong;
    [FieldOffset(0)] float @float;
    [FieldOffset(0)] double @double;
}
+3
5

. , , ? , , . , , , , .NET .

: . , , object ( , ). - , . , "" . ( - DLR, :)

+2

, , . , .

+2

" , unbox/box ?"

: , /. : ( , ).

: , " ", , , .

, , " ". , Framework 1.x. , BCL System.Object , .

( .)

+1

, , , : Box<T>. :

(1) T , T, , , , Equals.

(2) T # vb.net, T , , ( ++/CLI). , boxed Int32, . , ImmutableBox<T>, T, .

(3) , (, , IEnumerator<T>) , , , Equals ( ), . , , , - .

(4) T Box<T> T . , Object, vb.net, # .

(5) , param- Object[] , Int32 Box<Int32>. , , , , . , , , Box<T>, T a Box<T> ( Box<Box<T>>.

+1

, , . , . - , , :

, , , . structs ( ref out ), . , , .

, , , . x 17 x y, y 17 y x 18. , , , .

. .

. ? . object, # generics, -, . ; , double IEquatable IComparable. , , .

, ? , , , , . , CLR , , baaaaad.

, ? , , , . , "" - , , . ? , , XNA. , ; , , .

0

Source: https://habr.com/ru/post/1702988/


All Articles