如何获得变量的全局可见性

时间:2019-05-03 10:39:23

标签: c#

我得到了一个包含另一个类对象的类,该对象又又 创建事件处理程序。 现在,如果事件处理程序被触发,我需要在父类中运行一些代码。我该如何解决我的问题?

static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new windowsform1());
    }
}

public partial class windowsform1 : Form
{
    private filewatcher watcher;

    private void button_klick(object sender, EventArgs e)
    {
         watcher = new filewatcher(textbox.Text);
    }
}

public class filewatcher
{
    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    public filewatcher(string pfad)
    {
        //... some more code
            watcher.Created += OnChanged;

            // Begin watching.
            watcher.EnableRaisingEvents = true;
        }
    }

    //event file changed
    private static void OnChanged(object source, FileSystemEventArgs e)
    {
        //Do some stuff with the windowsform1-object in the main thread
    }
}

2 个答案:

答案 0 :(得分:0)

您需要在windowsform1中为在filewatcher中触发的事件添加事件处理程序

答案 1 :(得分:0)

您标记为正确的答案是一个懒惰的修正和一个错误的设计,从长远来看,您会注意到这样做的正确方法:

1-在子类上有一个事件处理程序。

    class ChildClass {
    EventHandler MyEventHandler { get; set; }
    ...

2-在父级的构造函数中将要执行的功能分配给子级的事件处理程序。

    childClass.MyEventHandler += MyParentFunction;

3-从子级调用事件处理程序,它将运行您在父级构造函数中预订的函数。

    class ChildClass {
    EventHandler MyEventHandler { get; set; }
    ...

    MyEventHandler?.Invoke();

来源https://docs.microsoft.com/en-us/dotnet/api/system.eventhandler?view=netframework-4.8