Checking delegates for null

后端 未结 6 1999
滥情空心
滥情空心 2021-02-04 11:48

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 Temperat         


        
6条回答
  •  一向
    一向 (楼主)
    2021-02-04 12:49

    First, you aren't actually publishing an event - so at the moment, your code is "at risk" of people messing it up completely. It should be:

    public event TemperatureChangeHandler CurrentTemperatureChanged;
    

    The name "CurrentTemperatureChanged" is important for data-binding (there is a convention that the runtime uses - given a property Foo, it will look for FooChanged). However, IMO this should just be regular EventHandler. Data-binding will look for EventHandler, but more importantly: you aren't actually giving any information in the event that the subscriber can't already get just by looking at obj.CurrentTemperature.

    I'll give the rest of the answer in terms of TemperatureChangeHandler, but I would encourage you (again) to switch to EventHandler:

    public event EventHandler CurrentTemperatureChanged;
    

    The approach:

    TemperatureChangeHandler handler = CurrentTemperatureChanged;
    if(handler != null) handler(value);
    

    is reasonable, but (as per other replies) there is a slim risk of callers that think they disconnected getting the event. Unlikely in reality.

    Another approach is an extension method:

    public static class TemperatureChangeExt {
        public static void SafeInvoke(this TemperatureChangeHandler handler,
                 float newTemperature) {
            if (handler != null) handler(newTemperature);
        }
    }
    

    Then in your class you can just use:

            if (currentTemperature != value) {
                currentTemperature = value;
                CurrentTemperatureChanged.SafeInvoke(value);
            }
    

提交回复
热议问题