Can you add an object to a c# watcher?

我的未来我决定 提交于 2019-12-11 23:20:39

问题


When i create a watcher i want to add an object to it that i can read during the watchers watcher_Created event?


回答1:


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.



来源:https://stackoverflow.com/questions/4683007/can-you-add-an-object-to-a-c-sharp-watcher

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!