简体   繁体   English

在单独的类/表单中使用引用的C#对象

[英]Using a referenced C# object in a seperate class/form

I've got a Windows Form program that creates a Config object which contains various configuration variables used by my program. 我有一个Windows Form程序,该程序创建一个Config对象,其中包含程序使用的各种配置变量。 Within the main form, it contains a button to open a new configuration form, where it passes the Config object as a reference - 在主表单中,它包含一个用于打开新配置表单的按钮,它将配置对象作为引用传递给它-

FormConfig button = new FormConfig(ref config);
            button.ShowDialog();

Now in the FormConfig class, I can access the Config object within the main constructor 现在在FormConfig类中,我可以在主构造函数中访问Config对象

public FormConfig(ref Config config)
        {
            InitializeComponent();
            // can access config.xyz OK here
        }

However within the new form, I've got a button that calls another function that needs to access the reference Config object, however I'm struggling to find a clean way to do so. 但是,在新表单中,我有一个按钮,该按钮调用另一个需要访问引用Config对象的函数,但是我一直在努力寻找一种做到这一点的干净方法。 I can create another Config object as part of the FormConfig class, and then copy the referenced Config to it in the main constructor, however then the original config object doesn't get updated. 我可以创建另一个Config对象作为FormConfig类的一部分,然后将引用的Config复制到主构造函数中,但是原始的config对象不会得到更新。

How can I achieve this? 我该如何实现?

PS apologies in advance if this is already answered, but my searches have so far failed to find a solution, possibly because I'm not sure what the correct search terms should be. 如果已回答了PS,请提前道歉,但是到目前为止,我的搜索未能找到解决方案,这可能是因为我不确定应该使用的搜索词是什么。

And the solution thanks to @cmos, is to declare the Config class as static, which negates the need to use any referencing or passing objects between classes/functions - 由于@cmos,解决方案是将Config类声明为静态,从而消除了在类/函数之间使用任何引用或传递对象的需要-

public static class Config
{
     public static bool SettingA = true;
}

Which means I can access and modify the Config object from anywhere within the same namespace with the following code, without needing to have a class instance - 这意味着我可以使用以下代码从同一名称空间中的任何位置访问和修改Config对象,而无需使用类实例-

Config.SettingA

Thanks to all those who helped point me in the right direction. 感谢所有帮助我指出正确方向的人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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