快速問題 即使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時,它將停止執行。 –