快速提问 即使SomeObject.SomeDelegateProperty为null并且不会发生invokation,是否会对someOtherDelegate进行求值?我假设没有,因为(?。)是停止执行如果为null但我需要确认。
SomeObject.SomeDelegateProperty?.Invoke(someOtherDelegate());
谢谢
答案 0 :(得分:2)
她的测试示例:
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_0013
,否则转到结束地址IL_001e
。< / p>
答案 1 :(得分:0)
当SomeObject.SomeDelegateProperty == null时,它将停止执行。 正如Jeroen van Langen评论的那样