سؤال

Consider the following:

Action<int, T> a1 = new Action<int, T>(_insert);

Action<int, T> a2 = new Action<int, T>(a1);

What is a2 referring to ? Is it a1, a shallow copy of a1 or is it a deep copy of a1 ?

هل كانت مفيدة؟

المحلول

a2 is referencing a1. Here is the IL:

.method private hidebysig static void Main() cil managed
{
    .entrypoint
    .maxstack 3
    .locals init (
        [0] class [mscorlib]System.Action a1,
        [1] class [mscorlib]System.Action a2)
    L_0000: nop 
    L_0001: ldnull 
    L_0002: ldftn void WebTools.ConsoleTest.Program::Main()
    L_0008: newobj instance void [mscorlib]System.Action::.ctor(object, native int)
    L_000d: stloc.0 
    L_000e: ldloc.0 
    L_000f: ldftn instance void [mscorlib]System.Action::Invoke() #1
    L_0015: newobj instance void [mscorlib]System.Action::.ctor(object, native int)
    L_001a: stloc.1 
    L_0020: nop 
    L_0021: ret 
}

At #1 the IL code is referencing a1's Invoke method and the instance a1 itself.

A shallow copy would mean that the contents of a1 are copied, but nothing is being copied. The object a1 is treated as a black-box. Therefore a2 will keep a1 alive with respect to GC.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top