对于空检查代表 [英] Checking delegates for null

查看:132
本文介绍了对于空检查代表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读了基本的C#3.0的书,想知道这是否是检查的代表为空的好方法:

I was reading the Essential C# 3.0 book and am wondering if this is a good way to check delegates for null?:

class Thermostat
{
    public delegate void TemperatureChangeHandler ( float newTemperature );

    public TemperatureChangeHandler OnTemperatureChange { get; set; }

    float currentTemperature;

    public float CurrentTemperature
    {
    	get { return this.currentTemperature; }
    	set
    	{
    		if ( currentTemperature != value )
    		{
    			currentTemperature = value;

    			TemperatureChangeHandler handler = OnTemperatureChange;

    			if ( handler != null )
    			{
    				handler ( value );
    			}
    		}
    	}
    }
}

解决方案是否变化,如果该类型是不可变的?我想也许有永恒,你就不会遇到这个线程问题。

Does the solution changes if the type is immutable? I figured maybe with immutability you wouldn't run into this threading problem.

推荐答案

已经有上这么多的讨论。

Original (somewhat inaccurate) Response:

There has been much discussion on this.

在短:你不能保证该处理器将是有效的,即使做这个拷贝/检查空/执行步

In short: you can't guarantee that the handler will be valid even by doing this copy/check for null/ execute step.

现在的问题是,如果OnTemperatureChange是未经注册的,你把它复制之间的时间,而你执行复制的时候,那么它可能是真的,你不希望听者被执行的。

The problem is, if OnTemperatureChange is unregistered between the time you copy it, and the time you execute the copy, then it's probably true that you don't want the listener to be executed anyway.

您可能也只是做的:

if (OnTemperatureChange != null )
{
    OnTemperatureChange ( value );
}

和处理空引用异常。

我有时会添加一个默认的处理程序,什么也不做,只是为了prevent的空引用异常,但增加了对性能的影响十分严重,特别是在没有注册任何其他处理的情况。

I sometimes add a default handler that does nothing, just to prevent the null reference exception, but that adds performance impact quite seriously, especially in the case where there is no other handler registered.

我推迟到埃里克利珀

我原来的答复也暗示使用默认的处理程序,但我不建议使用一个临时变量,现在我同意好做法也,每一篇文章。

My original response did allude to using default handlers, but I didn't recommend using a temp variable, which I now agree as good practice also, per the article.

这篇关于对于空检查代表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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