投放到Func对新Func? [英] Cast to Func vs new Func?

查看:44
本文介绍了投放到Func对新Func?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下两个语句之间是否有区别?他们俩都工作。

Is there any difference between the following two statement? They both work.

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


推荐答案

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

No, they both compile to exactly the same IL.

更容易看出您是否实际上给了lambda主体某些依赖状态的东西-否则编译器会为每个lambda缓存单个委托实例。但例如:

It's easier to see if you actually give the lambda body something that depends on state - otherwise the compiler caches a single delegate instance for each lambda. But for example:

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();
    }
}

现在在IL中进行 Cast 是:

.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

和IL的 New 是:

.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 调用相同,后者仅使用适当的编译器生成的方法。

As you can see, they're same apart from the ldftn call, which just uses the appropriate compiler-generated method.

这篇关于投放到Func对新Func?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆