你可以向c#监视器添加一个对象吗? [英] Can you add an object to a c# watcher?

查看:174
本文介绍了你可以向c#监视器添加一个对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我创建一个观察者,我想添加一个对象,我可以在观察者watcher_Created事件期间读取?

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
};

这里, o 表示你想要捕获(不必输入对象)。

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.

这篇关于你可以向c#监视器添加一个对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆