null 事件 += 不会导致错误。为什么这个 `null +=` 不是一个错误?

问题描述 投票:0回答:1

运行以下命令

delegate void GreetDelegateType();

public class Program {
    static GreetDelegateType GreetDelegate;
    static event GreetDelegateType GreetEvent;
    static void GreetInEnglish() {
        Console.WriteLine("Hello!");
    }
    public static void Main(string[] args) {
        if (GreetDelegate == null) {
            Console.WriteLine("GreetDelegate is null");
            GreetDelegate += GreetInEnglish;
        } else {
            Console.WriteLine("GreetDelegate is not null");
        }
        GreetDelegate();
        
        if (GreetEvent == null) {
            Console.WriteLine("GreetEvent is null");
            GreetEvent += GreetInEnglish;
        } else {
            Console.WriteLine("GreetEvent is not null");
        }
        GreetEvent();
    }
}

打印

GreetDelegate is null
Hello!
GreetEvent is null
Hello!

到控制台。既然

GreetDelegate
GreetEvent
都是
null
,为什么
GreetDelegate += GreetInEnglish;
GreetEvent += GreetInEnglish;
行不会导致错误呢?
null += anything>
感觉应该会导致错误。即使事件是
<null event> += 
add
是否也会调用
event
null
方法?


this 解释了

GreetDelegate
GreetEvent
是如何分配的
null

c# events null delegates field
1个回答
0
投票

C#使用+=运算符作为Combine方法,使用-=运算符作为Remove方法来实现委托操作。

+= 运算符的工作原理如下: 一个带有调用列表的新委托,该调用列表按顺序连接 a 和 b 的调用列表。如果 b 为 null,则返回 a;如果 a 为 null 引用,则返回 b;如果 a 和 b 均为 null 引用,则返回 null 引用。

您可以在下面查看更多信息。

https://learn.microsoft.com/en-us/dotnet/api/system.delegate?view=net-8.0

https://learn.microsoft.com/en-us/dotnet/api/system.delegate.combine?view=net-8.0

© www.soinside.com 2019 - 2024. All rights reserved.