开发者

Can you add an object to a c# watcher?

开发者 https://www.devze.com 2023-02-03 21:32 出处:网络
When i create a watcher i want to add an object to it that i can read during the watchers watcher_Created event?开发者_如何学运维You can just capture it in an anonymous delegate:

When i create a watcher i want to add an object to it that i can read during the watchers watcher_Created event?开发者_如何学运维


You can just capture it in an anonymous delegate:

object o;
var watcher = new FileSystemWatcher();
watcher.Created += (sender, e) => { 
    Console.WriteLine(o);
    // handle created event
};

Here, o represents the object that you want to capture (it doesn't have to be typed as object).

Note that this is effectively the same as

class Foo {
    private readonly object o;
    public Foo(object o) {
        this.o = o;
    }

    public void OnCreated(object sender, FileSystemEventArgs e) {
        Console.WriteLine(this.o);
        // handle event
    }
}

object o = null;
Foo foo = new Foo(o);
var watcher = new FileSystemWatcher();
watcher.Created += foo.OnCreated;

but we have let the compiler do the work for us. There are subtle differences.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号