【问题标题】:C# Elvis Operator - will the parameters be evaluated?C# Elvis Operator - 是否会评估参数?
【发布时间】:2017-08-01 09:37:50
【问题描述】:

快速提问 即使 SomeObject.SomeDelegateProperty 为 null 并且不会发生调用,是否会评估 someOtherDelegate?我假设没有,因为 (?.) 的目的是在 null 时停止执行,但我需要确认。

SomeObject.SomeDelegateProperty?.Invoke(someOtherDelegate());

谢谢

【问题讨论】:

  • SomeObject.SomeDelegateProperty == null时会停止执行。

标签: c# operators


【解决方案1】:

她我的测试例子:

internal class Program
{
    private static void Main( string[] args )
    {
        var SomeObject = new FakeClass();
        SomeObject.SomeDelegateProperty?.Invoke( someOtherDelegate() );
    }

    public static string someOtherDelegate()
    {
        return String.Empty;
    }

    public class FakeClass
    {
        public Action<string> SomeDelegateProperty;
    }
}

还有IL代码:

.method private hidebysig static void  Main(string[] args) cil managed
{
    .entrypoint
    // Размер кода:       31 (0x1f)
    .maxstack  2
    .locals init ([0] class StackOverflow.Examples.Program/FakeClass SomeObject)
    IL_0000:  nop
    IL_0001:  newobj     instance void 
    StackOverflow.Examples.Program/FakeClass::.ctor()
    IL_0006:  stloc.0
    IL_0007:  ldloc.0
    IL_0008:  ldfld      class [mscorlib]System.Action`1<string> 
    StackOverflow.Examples.Program/FakeClass::SomeDelegateProperty
    IL_000d:  dup
    IL_000e:  brtrue.s   IL_0013
    IL_0010:  pop
    IL_0011:  br.s       IL_001e
    IL_0013:  call       string      StackOverflow.Examples.Program::someOtherDelegate()
    IL_0018:  callvirt   instance void class 
    [mscorlib]System.Action`1<string>::Invoke(!0)
    IL_001d:  nop
    IL_001e:  ret
} // end of method Program::Main

您如何查看指令IL_000e: brtrue.s IL_0013 检查SomeDelegateProperty,如果它不为空,则在地址IL_0013 上调用someOtherDelegate,否则转到结束地址IL_001e

【讨论】:

  • 虽然我回答了,但您的答案在证明/解释方面更加完善,所以我将其标记为答案 - 感谢您的研究
【解决方案2】:

当 SomeObject.SomeDelegateProperty == null 时它将停止执行。 正如 Jeroen van Langen 评论的那样

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-20
    • 2023-03-04
    • 2013-10-27
    • 1970-01-01
    • 2013-01-02
    • 1970-01-01
    • 2017-02-03
    • 2011-11-05
    相关资源
    最近更新 更多