Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid anonymous methods in "dynamic" event subscription?

How could I refactor the method

private void ListenToPropertyChangedEvent(INotifyPropertyChanged source,
                                          string propertyName)
{
    source.PropertyChanged += (o, e) =>
    {
        if (e.PropertyName == propertyName)
            MyMagicMethod();
    };
}

if I wished to avoid using the anonymous method here?

like image 975
Jens Avatar asked Jun 29 '11 06:06

Jens


1 Answers

Implement the closure that is implicitly created by the lambda explicitly:

private void ListenToPropertyChangedEvent(INotifyPropertyChanged source,
                                          string propertyName)
{
    var listener = new MyPropertyChangedListener(propertyName);
    source.PropertyChanged += listener.Handle;
}

class MyPropertyChangedListener
{
    private readonly string propertyName;

    public MyPropertyChangedListener(string propertyName)
    {
        this.propertyName = propertyName;
    }

    public void Handle(object sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName == this.propertyName)
        {
            // do something
        }
    }
}
like image 64
dtb Avatar answered Sep 20 '22 06:09

dtb