gpt4 book ai didi

c# - 转换到 Func 与新 Func?

转载 作者:太空狗 更新时间:2023-10-30 00:19:07 27 4
gpt4 key购买 nike

下面两种说法有区别吗?他们都工作。

if ( ((Func<bool>)(()=>true))() ) { .... };
if ( new Func<bool>(()=>true)()) { .... };

最佳答案

不,它们都编译为完全相同的 IL。

更容易看出您是否真的为 lambda 主体提供了一些依赖于状态的东西——否则编译器会为每个 lambda 缓存一个委托(delegate)实例。但例如:

using System;

class Test
{
bool value = DateTime.Now.Hour == 10;

void Cast()
{
if (((Func<bool>)(() => value))())
{
Console.WriteLine("Yes");
}
}

void New()
{
if (new Func<bool>(() => value)())
{
Console.WriteLine("Yes");
}
}

static void Main()
{
new Test().Cast();
new Test().New();
}
}

现在 Cast 的 IL 是:

.method private hidebysig instance void  Cast() cil managed
{
// Code size 39 (0x27)
.maxstack 2
.locals init (bool V_0)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldftn instance bool Test::'<Cast>b__0'()
IL_0008: newobj instance void class [mscorlib]System.Func`1<bool>::.ctor(object,
native int)
IL_000d: callvirt instance !0 class [mscorlib]System.Func`1<bool>::Invoke()
IL_0012: ldc.i4.0
IL_0013: ceq
IL_0015: stloc.0
IL_0016: ldloc.0
IL_0017: brtrue.s IL_0026
IL_0019: nop
IL_001a: ldstr "Yes"
IL_001f: call void [mscorlib]System.Console::WriteLine(string)
IL_0024: nop
IL_0025: nop
IL_0026: ret
} // end of method Test::Cast

New 的 IL 是:

.method private hidebysig instance void  New() cil managed
{
// Code size 39 (0x27)
.maxstack 2
.locals init (bool V_0)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldftn instance bool Test::'<New>b__1'()
IL_0008: newobj instance void class [mscorlib]System.Func`1<bool>::.ctor(object,
native int)
IL_000d: callvirt instance !0 class [mscorlib]System.Func`1<bool>::Invoke()
IL_0012: ldc.i4.0
IL_0013: ceq
IL_0015: stloc.0
IL_0016: ldloc.0
IL_0017: brtrue.s IL_0026
IL_0019: nop
IL_001a: ldstr "Yes"
IL_001f: call void [mscorlib]System.Console::WriteLine(string)
IL_0024: nop
IL_0025: nop
IL_0026: ret
} // end of method Test::New

如您所见,除了 ldftn 调用外,它们是相同的,后者仅使用适当的编译器生成的方法。

关于c# - 转换到 Func 与新 Func?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24705925/

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