c# - 从委托(delegate)构造委托(delegate)。新的委托(delegate)指向什么?

标签 c# reference delegates deep-copy shallow-copy

考虑以下几点:

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

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

a2 指的是什么?它是 a1,a1 的浅拷贝还是 a1 的深拷贝?

最佳答案

a2 正在引用 a1。这是 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 
}

在 #1 处,IL 代码引用了 a1 的 Invoke 方法和实例 a1 本身。

浅拷贝意味着 a1 的内容被复制,但没有被复制。对象 a1 被视为黑盒。因此 a2 将使 a1 在 GC 方面保持事件状态。

关于c# - 从委托(delegate)构造委托(delegate)。新的委托(delegate)指向什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11382002/

相关文章:

function - 为什么一个 Func 有效而另一个(几乎相同)无效

c++ - 如何通过参数包传递引用?

javascript - 有没有办法在变量中存储对深层对象键的引用?

c# - 使用 Entity Framework 返回数据表

c# - 同时锁定多个对象

c++ - 为什么C++中没有 "NULL reference"?

delegates - 是否有可能扩展 System.Delegate?

jquery - 如何将 jQuery 事件添加到所有当前和 future 的元素?

c# - asp.net core 1 appsettings.production.json 不更新连接字符串

c# - 以特定语言以编程方式创建 sitecore 项目