简体   繁体   中英

C# Is it possible to use the weak event pattern with a static class?

I have a static class I was using because I didn't like the idea of passing around a gigantic settings file, but then I wished to be able to have instances subscribe to static events on the static class.

I was looking into using the PropertyChangedEventManager's AddListener method, but it needs an instance to add.

is this even possible? i'm on .net 4.0, in case it matters.

You can have a static event and have multiple instances subscribe to it. You'll just have to keep in mind all instances that are wired will get notified of event and their implementation invoked. This also can have issues in memory management, your instances won't go out of scope and get GC'd until they unwire themselves from the event.

Heres an example script to show:

delegate void Pop();
static event Pop PopEvent;

void Main()
{
    var t1= new Thing("firstone");
    var t2= new Thing("secondOne");

    //fire event
    PopEvent();
}

public class Thing
{
    public Thing(string name)
    {
        this.name = name;
        PopEvent += this.popHandler;
    }

    private string name="";

    public void popHandler()
    {
        Console.WriteLine("Event handled in {0}",this.name);
    }

}

Output:

Event handled in firstone Event handled in secondOne

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM