为什么代表空,而不是一个空表时,有没有用户? [英] Why are delegates null rather than an empty list when there is no subscriber?

查看:142
本文介绍了为什么代表空,而不是一个空表时,有没有用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释为什么.net框架小组决定,如果没有用户的委托应该是一个对象null而不是用空InvocationList?我想知道,导致这一决定的理由。

Can somebody explain why the .Net framework team decided that a delegate without subscribers should be null instead of an object with an empty InvocationList? I'd like to know the rationale that led to this decision.

void DoSomething()
{
    EventHandler handler = SomeEvent;
    if(handler != null)                   //why is this null-check necessary?
    {
        handler(this, EventArgs.Empty);
    }
}

感谢

推荐答案

在CLR的水平,代表领域和活动领域是常规领域。

On the CLR level, delegate fields and event fields are regular field.

就像字符串MyField的默认为,而不是,所以也动作MyField的默认为,而不是一个空的动作实例。

Just like string MyField defaults to null and not "", so too Action MyField defaults to null and not an empty Action instance.

这篇关于为什么代表空,而不是一个空表时,有没有用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆