クイック質問 SomeObject.SomeDelegatePropertyがnullでinvokationが発生しなくてもsomeOtherDelegateを評価できますか? nullの場合は(?)の実行を中止することですが、確認が必要なので、私は何もしません。 C#Elvis Operator - パラメータは評価されますか?
SomeObject.SomeDelegateProperty?.Invoke(someOtherDelegate());
あなたは
クイック質問 SomeObject.SomeDelegatePropertyがnullでinvokationが発生しなくてもsomeOtherDelegateを評価できますか? nullの場合は(?)の実行を中止することですが、確認が必要なので、私は何もしません。 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コード:
あなたが指示IL_000e: brtrue.s IL_0013
チェック
SomeDelegateProperty
とアドレスにそれnullでないコール
someOtherDelegate
場合を見ることができますどのように
.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_0013
それ以外の場合は、終了アドレスIL_001e
に移動します。
私は答えましたが、あなたの答えは証明/説明ではるかに洗練されていますので、私は答えとしてマークしています - 研究に感謝します –
それが実行を停止しますありがとうございました際SomeObject.SomeDelegateProperty == nullを。 のJeroenバンランゲンは
'SomeObject.SomeDelegateProperty == null'のときは実行を停止します。 –