简体   繁体   English

C# WinForms 在所有 Forms 中使用 class 的实例,每次都没有通过

[英]C# WinForms use instance of class in all Forms w/o passing everytime

I'm a newbie and im pretty sure its a dumb question but i couldnt find a thread which is solving exactly my problem or im simply to much of a newbie to understand, i dont know.我是一个新手,我很确定这是一个愚蠢的问题,但我找不到一个可以完全解决我的问题的线程,或者我只是让很多新手理解,我不知道。

My Problem :我的问题
I got a Login Form, when the login was successfully i create an instance of my "User" class and pass it to the mainForm.我得到了一个登录表单,当登录成功后,我创建了一个“用户”class 的实例并将其传递给 mainForm。 From now on i have to pass the object or the userid to any other form.从现在开始,我必须将 object 或用户 ID 传递给任何其他形式。

Is it possible to create the instance ONE time at the login and use it WITHOUT creating or passing it everytime?是否可以在登录时创建一次实例并使用它而不每次都创建或传递它?

Hope my question is clear and thanks in advance.希望我的问题很清楚,并提前感谢。

The most easiest way to achieve that is putting your class in place where all forms can see it.Like Program.cs实现这一目标的最简单方法是将 class 放在所有 forms 都可以看到的地方。像 Program.cs

static class Program 
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new IzborPretrage());
    }
    public static MyClass GlobalStuff { get; set; }
}

You can then set it like:然后,您可以将其设置为:

Program.GlobalStuff = yourClassInstance;

Another way would be to create a singleton class: You can find example here另一种方法是创建 singleton class:您可以在此处找到示例

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

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