Глобальные переменные c windows form

They have already answered how to use a global variable.

I will tell you why the use of global variables is a bad idea as a result of this question carried out in stackoverflow in Spanish.

Explicit translation of the text in Spanish:

Impact of the change

The problem with global variables is that they create hidden dependencies. When it comes to large applications, you yourself do not know / remember / you are clear about the objects you have and their relationships.

So, you can not have a clear notion of how many objects your global variable is using. And if you want to change something of the global variable, for example, the meaning of each of its possible values, or its type? How many classes or compilation units will that change affect? If the amount is small, it may be worth making the change. If the impact will be great, it may be worth looking for another solution.

But what is the impact? Because a global variable can be used anywhere in the code, it can be very difficult to measure it.

In addition, always try to have a variable with the shortest possible life time, so that the amount of code that makes use of that variable is the minimum possible, and thus better understand its purpose, and who modifies it.

A global variable lasts for the duration of the program, and therefore, anyone can use the variable, either to read it, or even worse, to change its value, making it more difficult to know what value the variable will have at any given program point. .

Order of destruction

Another problem is the order of destruction. Variables are always destroyed in reverse order of their creation, whether they are local or global / static variables (an exception is the primitive types, int,enums, etc., which are never destroyed if they are global / static until they end the program).

The problem is that it is difficult to know the order of construction of the global (or static) variables. In principle, it is indeterminate.

If all your global / static variables are in a single compilation unit (that is, you only have a .cpp), then the order of construction is the same as the writing one (that is, variables defined before, are built before).

But if you have more than one .cpp each with its own global / static variables, the global construction order is indeterminate. Of course, the order in each compilation unit (each .cpp) in particular, is respected: if the global variableA is defined before B,A will be built before B, but It is possible that between A andB variables of other .cpp are initialized. For example, if you have three units with the following global / static variables:

Image1

In the executable it could be created in this order (or in any other order as long as the relative order is respected within each .cpp):

Image2

Why is this important? Because if there are relations between different static global objects, for example, that some use others in their destructors, perhaps, in the destructor of a global variable, you use another global object from another compilation unit that turns out to be already destroyed ( have been built later).

Hidden dependencies and * test cases *

I tried to find the source that I will use in this example, but I can not find it (anyway, it was to exemplify the use of singletons, although the example is applicable to global and static variables). Hidden dependencies also create new problems related to controlling the behavior of an object, if it depends on the state of a global variable.

Imagine you have a payment system, and you want to test it to see how it works, since you need to make changes, and the code is from another person (or yours, but from a few years ago). You open a new main, and you call the corresponding function of your global object that provides a bank payment service with a card, and it turns out that you enter your data and they charge you. How, in a simple test, have I used a production version? How can I do a simple payment test?

After asking other co-workers, it turns out that you have to «mark true», a global bool that indicates whether we are in test mode or not, before beginning the collection process. Your object that provides the payment service depends on another object that provides the mode of payment, and that dependency occurs in an invisible way for the programmer.

In other words, the global variables (or singletones), make it impossible to pass to «test mode», since global variables can not be replaced by «testing» instances (unless you modify the code where said code is created or defined). global variable, but we assume that the tests are done without modifying the mother code).

Solution

This is solved by means of what is called * dependency injection *, which consists in passing as a parameter all the dependencies that an object needs in its constructor or in the corresponding method. In this way, the programmer ** sees ** what has to happen to him, since he has to write it in code, making the developers gain a lot of time.

If there are too many global objects, and there are too many parameters in the functions that need them, you can always group your «global objects» into a class, style * factory *, that builds and returns the instance of the «global object» (simulated) that you want , passing the factory as a parameter to the objects that need the global object as dependence.

If you pass to test mode, you can always create a testing factory (which returns different versions of the same objects), and pass it as a parameter without having to modify the target class.

But is it always bad?

Not necessarily, there may be good uses for global variables. For example, constant values ​​(the PI value). Being a constant value, there is no risk of not knowing its value at a given point in the program by any type of modification from another module. In addition, constant values ​​tend to be primitive and are unlikely to change their definition.

It is more convenient, in this case, to use global variables to avoid having to pass the variables as parameters, simplifying the signatures of the functions.

Another can be non-intrusive «global» services, such as a logging class (saving what happens in a file, which is usually optional and configurable in a program, and therefore does not affect the application’s nuclear behavior), or std :: cout,std :: cin or std :: cerr, which are also global objects.

Any other thing, even if its life time coincides almost with that of the program, always pass it as a parameter. Even the variable could be global in a module, only in it without any other having access, but that, in any case, the dependencies are always present as parameters.

Answer by: Peregring-lk

1 / 1 / 1

Регистрация: 07.12.2013

Сообщений: 67

1

Глобальная переменная в формах

21.04.2014, 15:45. Показов 38920. Ответов 9


Студворк — интернет-сервис помощи студентам

Есть две формы. Где и как объявить глобальную переменную, чтобы в первой форме туда значение записывалось, а во второй форме считывалось и применялось?

Спасибо.



0



349 / 262 / 65

Регистрация: 07.04.2014

Сообщений: 1,603

21.04.2014, 16:00

2

Как связаны 1я и 2я формы? 1я вызывается из 2й?



0



1 / 1 / 1

Регистрация: 07.12.2013

Сообщений: 67

21.04.2014, 16:01

 [ТС]

3

Вторая вызывается первой



0



993 / 891 / 354

Регистрация: 24.03.2014

Сообщений: 2,381

Записей в блоге: 2

21.04.2014, 16:02

4

Без разницы, вопрос лишь в порядке записи и считывания будет



0



1 / 1 / 1

Регистрация: 07.12.2013

Сообщений: 67

21.04.2014, 16:05

 [ТС]

5

Так где и как переменную объявить то)))



0



Spawn

993 / 891 / 354

Регистрация: 24.03.2014

Сообщений: 2,381

Записей в блоге: 2

21.04.2014, 16:13

6

Лучший ответ Сообщение было отмечено dimonkhr как решение

Решение

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Form1 : Form
{
    public int myGlobalForm1Value;
    
    void Method()
    {
        Form2 frm2 = new Form2();
        frm2.myGlobalForm2Value = 0;
        frm2.PublicMethod(this);
    }
}
 
public class Form2 : Form
{
    public int myGlobalForm2Value;
 
    public void PublicMethod(Form1 frm)
    {
        int someValue = frm.myGlobalForm1Value;
    }
}

Добавлено через 55 секунд
Где удобнее, где требуется, в зависимости от того, как вызываете… Мы не экстрасенсы, но явно им станем.



1



63 / 63 / 28

Регистрация: 18.03.2014

Сообщений: 794

21.04.2014, 16:31

7

Глобальные переменные это плохо. Для передачи данных между формами почитайте здесь



0



Администратор

Эксперт .NET

9414 / 4700 / 759

Регистрация: 17.04.2012

Сообщений: 9,544

Записей в блоге: 14

21.04.2014, 16:49

8

Цитата
Сообщение от igor_fl
Посмотреть сообщение

Глобальные переменные это плохо.

Особенно плохо потому, что в C# их не существует.



0



63 / 63 / 28

Регистрация: 18.03.2014

Сообщений: 794

21.04.2014, 17:37

9

имел в виду поля public)



0



2149 / 1286 / 516

Регистрация: 04.03.2014

Сообщений: 4,092

21.04.2014, 18:22

10

igor_fl, для передач между формами хорошо. Если нужно только первой форме брать данные у второй — то лучше автосвойство с закрытым сеттером.
а если связь дуплексная то по сути не важно поле это или свойство



0



  • Remove From My Forums
  • Question

  • I have this problem.. my main form class (MainForm) declares some variables that should be global, in a sense.  Let’s say my app, at startup, loads a bunch of user data.. into a list (List<UserInfo>).  I want that list available application-wide.  So if a preferences dialog opens up, and it needs to populate a ListView with that List<UserInfo>, it can.

    What is the best way to achieve this, in C#?

Answers

  • Go to Project -> Add Class.  Name your class Variables.  Here is an example:

    using System;
    using System.Collections.Generic;
    using System.Text;

    namespace YourNamespaceName
    {
        class Variables
        {
            public static string var = «»;
        }
    }

    then to call on your variable from any code just access it like:  Variables.var

  • Hi there,

    Assuming you meant using Model-View-Controller (MVC) then I’ll give you the quick 10 cent tour.

    Basically, your data abstraction, i.e. non-user interface type, exposes some (or all) of the data to interested parties and to notifiy those parties when the data changes. This is the Model part of MVC.

    The View part of MVC is any of your user interface types that are interested in the data (Model). You could have some (or all) of your forms/controls etc, become an interested party in the data represented in the Model. How you do this is up to you but you could just pass a reference to the Model into the constructor (or initialiser) of your form. You could be notified of changes in data by having events on the type representing your Model and subscribing to them on your user interface types.

    What this basically means is that if FormA modifies the data, then FormB can receive notification of the modified data and update itself accordingly.

    The Controller part of MVC can be thought of as the event mechanism for update notification, but it also takes into account formatting and some other detailed activites. You can probably ignore this in your implementation.

    Hence to apply it to your particular situation, instead of all your forms and dialogs having access to each other’s controls (which will be a maintenance headache), they simply modify a central model and all other controls reflect changes made to the model.

    My descriptive skills are somewhat lacking but if you want any further information there are many articles on MVC and similar design patterns (producer-consumer, client-subscriber etc) that can be found using your search engine of choice.

How do I declare global variables in Visual C#?

asked Nov 27, 2009 at 1:25

neuromancer's user avatar

neuromancerneuromancer

53.9k79 gold badges166 silver badges224 bronze badges

1

How about this

public static class Globals {
    public static int GlobalInt { get; set; }
}

Just be aware this isn’t thread safe. Access like Globals.GlobalInt

This is probably another discussion, but in general globals aren’t really needed in traditional OO development. I would take a step back and look at why you think you need a global variable. There might be a better design.

Himanshu's user avatar

Himanshu

31.9k31 gold badges111 silver badges133 bronze badges

answered Nov 27, 2009 at 1:28

Bob's user avatar

4

A public static field is probably the closest you will get to a global variable

public static class Globals
{
  public static int MyGlobalVar = 42;
}

However, you should try to avoid using global variables as much as possible as it will complicate your program and make things like automated testing harder to achieve.

answered Nov 27, 2009 at 1:32

JohannesH's user avatar

JohannesHJohannesH

6,4405 gold badges37 silver badges71 bronze badges

Use the const keyword:

public const int MAXIMUM_CACHE_SIZE = 100;

Put it in a static class eg

public class Globals
{
    public const int MAXIMUM_CACHE_SIZE = 100;
}

And you have a global variable class :)

Bob's user avatar

Bob

97.9k29 gold badges122 silver badges130 bronze badges

answered Nov 27, 2009 at 1:28

Russell's user avatar

RussellRussell

17.5k23 gold badges82 silver badges126 bronze badges

4

The nearest you can do this in C# is to declare a public variable in a public static class. But even then, you have to ensure the namespace is imported, and you specify the class name when using it.

answered Nov 27, 2009 at 1:31

Mark Bertenshaw's user avatar

Mark BertenshawMark Bertenshaw

5,5942 gold badges27 silver badges40 bronze badges

Одним из ключевых аспектов разработки приложений на платформе .NET является использование форм Windows (WinForms). Эти формы предоставляют удобный интерфейс для взаимодействия с пользователем и позволяют создавать разнообразные приложения — от простых десктопных приложений до сложных корпоративных систем.

Одной из часто задаваемых вопросов при работе с WinForms является вопрос о создании глобальных переменных. Глобальная переменная — это переменная, которая доступна из любой части программы и может быть использована в любом месте.

В этой статье мы рассмотрим, как создать глобальную переменную в WinForms, а также обсудим некоторые важные моменты, связанные с использованием глобальных переменных.

Почему нужно создавать глобальные переменные?

Перед тем, как перейти к созданию глобальных переменных в WinForms, давайте рассмотрим, почему мы это делаем.

Как правило, глобальные переменные используются для хранения данных, которые должны быть доступны в разных частях программы. Например, если у нас есть переменная, которая содержит информацию о текущем пользователе, мы можем использовать глобальную переменную для сохранения этой информации и обращаться к ней из любой части программы.

Кроме того, глобальные переменные позволяют избежать дублирования кода. Вместо того, чтобы объявлять одну и ту же переменную в разных местах программы, мы можем объявить ее только один раз и использовать ее везде, где это необходимо.

Как создать глобальную переменную в WinForms?

Создание глобальной переменной в WinForms — это достаточно простой процесс. Нам нужно объявить переменную в классе формы и задать ей модификатор доступа public.

Вот пример:

public partial class Form1 : Form
{
public int globalVariable;

public Form1()
{
InitializeComponent();
}
}

В этом примере мы создаем класс Form1, который наследуется от класса Form. Мы также объявляем глобальную переменную globalVariable типа int.

Для того чтобы эта переменная была доступна из других классов и форм, мы устанавливаем ее модификатор доступа public. Теперь мы можем получить доступ к этой переменной из любой части программы.

Некоторые часто задаваемые вопросы

1. Можно ли использовать глобальные переменные в многопоточном приложении?

Да, можно. Но необходимо учитывать, что глобальные переменные в многопоточном приложении могут быть доступны для изменения одновременно из нескольких потоков. Это может привести к проблемам синхронизации и потенциальным ошибкам. Поэтому при использовании глобальных переменных в многопоточном приложении необходимо соблюдать правила безопасности потоков.

2. Какие другие способы хранения данных можно использовать в WinForms?

В WinForms существует множество способов хранения данных. Например, мы можем использовать базы данных, файлы конфигураций, реестр Windows или файлы. Какой способ выбирать зависит от требований конкретного приложения и задач, которые он решает.

3. Как использовать глобальную переменную из другого класса?

Чтобы использовать глобальную переменную из другого класса, необходимо сначала создать экземпляр класса, в котором эта переменная объявлена. Затем мы можем обращаться к этой переменной через экземпляр класса. Вот пример:

public partial class Form1 : Form
{
public int globalVariable;

public void SomeMethod()
{
Form2 form2 = new Form2();
form2.globalVariable = globalVariable;
}
}

В этом примере мы создаем экземпляр класса Form2 и устанавливаем его глобальную переменную globalVariable равной глобальной переменной globalVariable класса Form1.

Заключение

Глобальные переменные являются очень полезным инструментом при разработке приложений на платформе .NET. Они позволяют хранить данные, которые должны быть доступны в разных частях программы, избежать дублирования кода и упростить процесс программирования. Однако при использовании глобальных переменных необходимо учитывать их потенциальные проблемы и соблюдать правила безопасности потоков.

  • Главное меню системы windows 4 буквы
  • Главный элемент операционной системы windows
  • Главные программы для windows 10
  • Главные отличия windows от linux
  • Главное меню операционной системы windows