Объявление глобальной переменной windows form c

I want some variables to be global across the project and accessible in every form. How can I do this?

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. Показов 35106. Ответов 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



991 / 889 / 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

991 / 889 / 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

9356 / 4638 / 755

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

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

Записей в блоге: 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



2146 / 1283 / 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.

      1. Настройка формы

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

В
результате открывается окно со свойствами
формы.

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

Внимание.
В конструкторе форм можно изменять
размеры формы, но нельзя менять ее
местоположение.

Чтобы
отобразить форму Windows Forms в конструкторе

дважды щелкните форму в Обозревателе
решений.

        1. Просмотр кода для формы

Перейти
к коду для формы можно одним из следующих
способов:

  • В
    Обозревателе
    решений выберите форму и нажмите кнопку
    Просмотреть код.

  • В
    Обозревателе решений в контекстном
    меню к форме выберите пункт Перейти к
    коду.

  • Если
    фокус находится в конструкторе, нажмите
    клавишу F7 для переключения в режим
    Редактор
    кода.

Примечание

Двойной
щелчок формы или ее элемента управления
в конструкторе также переключает в
режим Редактора
кода,
но при этом добавляет обработчик событий
по умолчанию для этого элемента
управления. Например, двойной щелчок
элемента управления Button
приводит к отображению Редактора
кода
и добавляет обработчик событий
Button_Click.

        1. Создание глобальной переменной класса Form

Пусть
имеется форма Form1. Обратиться программно
в коде непосредственно к Form1
в С# нельзя. Form1
– это класс. Для обращения к форме
необходимо завести переменную этого
класса.

Создать
глобальную переменную для формы можно
несколькими способами:

Способ1
Создать глобальную переменную класса
Form, а далее при инициализации прописать
ее принадлежность классу Form1.

Чтобы
создать глобальную переменную формы
этим способом необходимо

  1. в
    пространстве решения в любом месте
    после описания формы прописать код

public
class
имя_класса

{

public static Form
имя_переменной;

}

например:

namespace
Metodichka

{

…………….

public class glob

{

public
static Form frm;

}

}

Провести
инициализацию переменной:

glob.frm = new Form1();

Способ2
Создать сразу переменную заданного
класса:

public
class имя_класса

{

public
static Form имя_перем = new имя_класса_формы();

}

Пример:

public class glob

{

public
static Form frm=new Form1();

}

        1. Переименование формы

Для
переименования формы необходимо изменить
значение свойства Text в окне Свойства.

Программным
путем переименование формы можно
произвести с помощью команды:

Имя_переменной_формы.Text
= «Новое название»;

Пример:

glob.frm.Text
= «Моя первая форма»;

Примечание.
Исключение составляет начальная форма.

Чтобы
переименовать программным способом
начальную форму необходимо переменную
этой формы создать в файле program.cs,
например:

namespace
Metodichka

{//
Создаем глобальную переменную

public static class glob

{

public static Form frm1;

}

static class Program

{

..

static void Main()

{

Application.EnableVisualStyles();

//
инициализируем переменную

glob.frm1
= new Form1();

//запускаем
проект

Application.Run(glob.frm1);

}

}

}

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]

  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • 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.

  • 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.

Область видимости (контекст) переменных и констант

Последнее обновление: 10.11.2021

Каждая переменная доступна в рамках определенного контекста или области видимость. Вне этого контекста переменная уже не существует.

Существуют различные контексты:

  • Контекст класса. Переменные, определенные на уровне класса, доступны в любом методе этого класса. Их еще называют глобальными переменными или полями

  • Контекст метода. Переменные, определенные на уровне метода, являются локальными и доступны только в рамках данного метода. В других методах они недоступны

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

Например, пусть код программы определен следующим образом:

Person tom = new();
tom.PrintName();
tom.PrintSurname();

class Person                            // начало контекста класса
{
    string type = "Person";             // переменная уровня класса
    public void PrintName()             // начало контекста метода PrintName
    {
        string name = "Tom";            // переменная уровня метода

        {                               // начало контекста блока кода
            string shortName = "Tomas"; // переменная уровня блока кода
            Console.WriteLine(type);    // в блоке доступна переменная класса
            Console.WriteLine(name);    // в блоке доступна переменная окружающего метода
            Console.WriteLine(shortName);// в блоке доступна переменная этого же блока
        }                               // конец контекста блока кода, переменная shortName уничтожается

        Console.WriteLine(type);        // в методе доступна переменная класса
        Console.WriteLine(name);        // в методе доступна переменная этого же метода
        //Console.WriteLine(shortName); //так нельзя, переменная c определена в блоке кода
        //Console.WriteLine(surname);     //так нельзя, переменная surname определена в другом методе

    }       // конец контекста метода PrintName, переменная name уничтожается

    public void PrintSurname()      // начало контекста метода PrintSurname
    {
        string surname = "Smith";   // переменная уровня метода

        Console.WriteLine(type);        // в методе доступна переменная класса
        Console.WriteLine(surname);     // в методе доступна переменная этого же метода 
    }       // конец конекста метода PrintSurname, переменная surname уничтожается

}   // конец контекста класса, переменная type уничтожается

Здесь определенно четыре переменных: type, name, shortName и surname. Каждая из них существует в своем контексте. Переменная type
существует в контексте всего класса Person и доступна в любом месте и блоке кода в методах PrintName и PrintSurname.

Переменная name существует только в рамках метода PrintName. Также как и переменная surname существует в
рамках метода PrintSurname. В методе PrintName мы не можем обратиться к переменной surname, так как она в другом контексте.

Переменная shortName существует только в блоке кода, границами которого являются открывающая и закрывающая фигурные
скобки. Вне его границ переменная shortName не существует и к ней нельзя обратиться.

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

При работе с переменными надо учитывать, что локальные переменные, определенные в методе или в блоке кода, скрывают переменные уровня класса, если их имена совпадают:

class Person 
{
    string name = "Tom";             // переменная уровня класса
    public void PrintName() 
    {
        string name = "Tomas";      // переменная уровня метода скрывает переменную уровня класса

        Console.WriteLine(name);    // Tomas
    } 
}

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

How do I declare a variable so that every class (*.cs) can access its content, without an instance reference?

TylerH's user avatar

TylerH

20.5k62 gold badges75 silver badges97 bronze badges

asked Jan 16, 2013 at 21:26

masjum's user avatar

0

In C# you cannot define true global variables (in the sense that they don’t belong to any class).

This being said, the simplest approach that I know to mimic this feature consists in using a static class, as follows:

public static class Globals
{
    public const Int32 BUFFER_SIZE = 512; // Unmodifiable
    public static String FILE_NAME = "Output.txt"; // Modifiable
    public static readonly String CODE_PREFIX = "US-"; // Unmodifiable
}

You can then retrieve the defined values anywhere in your code (provided it’s part of the same namespace):

String code = Globals.CODE_PREFIX + value.ToString();

In order to deal with different namespaces, you can either:

  • declare the Globals class without including it into a specific namespace (so that it will be placed in the global application namespace);
  • insert the proper using directive for retrieving the variables from another namespace.

answered Jan 16, 2013 at 21:43

Tommaso Belluzzo's user avatar

Tommaso BelluzzoTommaso Belluzzo

22.9k8 gold badges71 silver badges97 bronze badges

5

You can have static members if you want:

public static class MyStaticValues
{
   public static bool MyStaticBool {get;set;}
}

Jason Ellingsworth's user avatar

answered Jan 16, 2013 at 21:28

Federico Berasategui's user avatar

8

First examine if you really need a global variable instead using it blatantly without consideration to your software architecture.

Let’s assuming it passes the test. Depending on usage, Globals can be hard to debug with race conditions and many other «bad things», it’s best to approach them from an angle where you’re prepared to handle such bad things. So,

  1. Wrap all such Global variables into a single static class (for manageability).
  2. Have Properties instead of fields(=’variables’). This way you have some mechanisms to address any issues with concurrent writes to Globals in the future.

The basic outline for such a class would be:

public class Globals
{
    private static bool _expired;
    public static bool Expired 
    {
        get
        {
            // Reads are usually simple
            return _expired;
        }
        set
        {
            // You can add logic here for race conditions,
            // or other measurements
            _expired = value;
        }
    }
    // Perhaps extend this to have Read-Modify-Write static methods
    // for data integrity during concurrency? Situational.
}

Usage from other classes (within same namespace)

// Read
bool areWeAlive = Globals.Expired;

// Write
// past deadline
Globals.Expired = true;

1

A useful feature for this is using static

As others have said, you have to create a class for your globals:

public static class Globals {
    public const float PI = 3.14;
}

But you can import it like this in order to no longer write the class name in front of its static properties:

using static Globals;
[...]
Console.WriteLine("Pi is " + PI);

answered Jun 12, 2019 at 19:50

Zotta's user avatar

ZottaZotta

2,4331 gold badge21 silver badges27 bronze badges

1

How do I declare a variable so that every class (*.cs) can access its content, without an instance reference?

TylerH's user avatar

TylerH

20.5k62 gold badges75 silver badges97 bronze badges

asked Jan 16, 2013 at 21:26

masjum's user avatar

0

In C# you cannot define true global variables (in the sense that they don’t belong to any class).

This being said, the simplest approach that I know to mimic this feature consists in using a static class, as follows:

public static class Globals
{
    public const Int32 BUFFER_SIZE = 512; // Unmodifiable
    public static String FILE_NAME = "Output.txt"; // Modifiable
    public static readonly String CODE_PREFIX = "US-"; // Unmodifiable
}

You can then retrieve the defined values anywhere in your code (provided it’s part of the same namespace):

String code = Globals.CODE_PREFIX + value.ToString();

In order to deal with different namespaces, you can either:

  • declare the Globals class without including it into a specific namespace (so that it will be placed in the global application namespace);
  • insert the proper using directive for retrieving the variables from another namespace.

answered Jan 16, 2013 at 21:43

Tommaso Belluzzo's user avatar

Tommaso BelluzzoTommaso Belluzzo

22.9k8 gold badges71 silver badges97 bronze badges

5

You can have static members if you want:

public static class MyStaticValues
{
   public static bool MyStaticBool {get;set;}
}

Jason Ellingsworth's user avatar

answered Jan 16, 2013 at 21:28

Federico Berasategui's user avatar

8

First examine if you really need a global variable instead using it blatantly without consideration to your software architecture.

Let’s assuming it passes the test. Depending on usage, Globals can be hard to debug with race conditions and many other «bad things», it’s best to approach them from an angle where you’re prepared to handle such bad things. So,

  1. Wrap all such Global variables into a single static class (for manageability).
  2. Have Properties instead of fields(=’variables’). This way you have some mechanisms to address any issues with concurrent writes to Globals in the future.

The basic outline for such a class would be:

public class Globals
{
    private static bool _expired;
    public static bool Expired 
    {
        get
        {
            // Reads are usually simple
            return _expired;
        }
        set
        {
            // You can add logic here for race conditions,
            // or other measurements
            _expired = value;
        }
    }
    // Perhaps extend this to have Read-Modify-Write static methods
    // for data integrity during concurrency? Situational.
}

Usage from other classes (within same namespace)

// Read
bool areWeAlive = Globals.Expired;

// Write
// past deadline
Globals.Expired = true;

1

A useful feature for this is using static

As others have said, you have to create a class for your globals:

public static class Globals {
    public const float PI = 3.14;
}

But you can import it like this in order to no longer write the class name in front of its static properties:

using static Globals;
[...]
Console.WriteLine("Pi is " + PI);

answered Jun 12, 2019 at 19:50

Zotta's user avatar

ZottaZotta

2,4331 gold badge21 silver badges27 bronze badges

1

Где я должен объявить переменные, которые я хотел бы использовать в формах Windows?

    private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {

int iMyvariable = 1;

}

private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {

iMyvariable++;
}

Запуск кода дает следующую ошибку:

ошибка C2065: «iMyvariable»: необъявленный идентификатор

-2

Решение

В вашем текущем коде iMyvariable сохраняется как локальная переменная, а не как глобальная переменная. За пределами скобок вокруг обработчика событий он перестает существовать.

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

Ваш код должен выглядеть примерно так:

public class something{

int myVariable;
private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {

iMyvariable = 1;

}

private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {

iMyvariable++;
}
}

2

Другие решения

Других решений пока нет …

Понравилась статья? Поделить с друзьями:
  • Объемный указатель мыши для windows 10
  • Объемный рабочий стол для windows 10
  • Объемный звук для наушников windows 10
  • Объемные объекты в windows 10 что это такое
  • Объем флешки для резервной копии windows 10