gpt4 book ai didi

c# - 委托(delegate)分配是否在 C# 中创建新副本?

转载 作者:行者123 更新时间:2023-11-30 15:25:59 25 4
gpt4 key购买 nike

我读了一篇关于 C# 和性能注意事项的文章 ( here )

文中说委托(delegate)赋值会触发内存分配,例如:

every single local variable assignment like "Func fn = Fn" creates a new instance of the delegate class Func on the heap

我想知道这是否属实,如果属实 - 如何实现?我不熟悉引用赋值可以在 C# 中触发额外内存分配的任何方式。

最佳答案

这篇文章是对的。很容易测试:

static void Main(string[] args)
{
Action<string[]> main = Main;
Action<string[]> main2 = Main;
Console.WriteLine(object.ReferenceEquals(main, main2)); // False
}

http://ideone.com/dgNxPn

如果您查看生成的 IL 代码 http://goo.gl/S47Wfy , 很清楚会发生什么:

    IL_0002: ldftn void Test::Main(string[])
IL_0008: newobj instance void class [mscorlib]System.Action`1<string[]>::.ctor(object, native int)
IL_000d: stloc.0
IL_000e: ldnull

IL_000f: ldftn void Test::Main(string[])
IL_0015: newobj instance void class [mscorlib]System.Action`1<string[]>::.ctor(object, native int)
IL_001a: stloc.1

所以有两个 newobj instance void class [mscorlib]System.Action1::.ctor(object, native int)`

请注意,您是对的,这是违反直觉的:

public class TestEvent
{
public event Action Event;

public TestEvent()
{
Action d1 = Print;
Action d2 = Print;

// The delegates are distinct
Console.WriteLine("d1 and d2 are the same: {0}", object.ReferenceEquals(d1, d2));

Event += d1;
Event -= d2;

// But the second one is able to remove the first one :-)
// (an event when is empty is null)
Console.WriteLine("d2 was enough to remove d1: {0}", Event == null);
}

public void Print()
{
Console.WriteLine("TestEvent");
}
}

event 为例,您可以使用“等效但不相同”的委托(delegate)来删除另一个委托(delegate),如示例所示。参见 https://ideone.com/xeJ6LO

关于c# - 委托(delegate)分配是否在 C# 中创建新副本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30155153/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com