快速问题 即使SomeObject.SomeDelegateProperty为null且invokation不会发生,是否会评估someOtherDelegate?我假设没有,因为(?。)的意思是停止执行,如果为空,但我需要确认。C#Elvis Operator - 参数是否会被评估?
SomeObject.SomeDelegateProperty?.Invoke(someOtherDelegate());
谢谢
快速问题 即使SomeObject.SomeDelegateProperty为null且invokation不会发生,是否会评估someOtherDelegate?我假设没有,因为(?。)的意思是停止执行,如果为空,但我需要确认。C#Elvis Operator - 参数是否会被评估?
SomeObject.SomeDelegateProperty?.Invoke(someOtherDelegate());
谢谢
她我的测试例子:
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
,如果它的地址不为空呼someOtherDelegate
否则转到末尾地址IL_001e
。
尽管我回答了,但您的答案更加精确,并附有证明/解释,因此我将其标记为答案 - 感谢您的研究 –
它将停止执行时SomeObject.SomeDelegateProperty == NULL。 作为吉荣面包车Langen的评论
当SomeObject.SomeDelegateProperty == null时,它将停止执行。 –