简体   繁体   English

如何在2种形式之间共享变量? 项目中的全局变量

[英]how to share a Variable between 2 form? global variable in the project

hi i want to share a variable between 2 form. 您好我想在2种形式之间共享一个变量。 2 forms is in the one project. 一个项目中有2种形式。 In fact,i want a global variable in the project how can i do it? 实际上,我想要项目中的全局变量怎么办?

Language: c# .net 语言:c#.net

Thanks 谢谢

Create a static class with static field/property like following: 创建具有静态字段/属性的静态类,如下所示:

public static class DataContainer
{
    public static Int32 ValueToShare;
}

use it in multiple forms like following: 以多种形式使用它,如下所示:

    public void Form1_Method()
    {
        DataContainer.ValueToShare = 10;
    }

    public void Form2_Method()
    {
        MessageBox.Show(DataContainer.ValueToShare.ToString());
    }

创建一个公共静态属性/方法/变量。

You can create a static class with static properties inside that. 您可以在其中创建带有static propertiesstatic class That will do it. 这样就可以了。

The most straight forward way is to pass the variable to the forms. 最直接的方法是将变量传递给表单。

It's hard to get into too much detail without knowing what your program does and how the forms are loaded, but I'd have the forms accept an argument in the constructor or something. 在不知道您的程序做什么以及如何加载表单的情况下,很难过分详细,但是我会让表单在构造函数中接受参数。 If the argument is a reference type, both forms would reference the same data. 如果参数是引用类型,则两种形式都将引用相同的数据。

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

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