Как использовать переменную из другого метода? - C#
Формулировка задачи:
Есть метод
Как переменную "put" использоват в этом конструкторе?
Листинг программы
- public static void Put()
- {
- string put = Console.ReadLine();
- if (put == "default") put = @"Dictionary.txt";
- }
Листинг программы
- public Translator(int direction)
- {
- string[] dictionary = File.ReadAllLines(@"Dictionary.txt", Encoding.Default);
- foreach (string line in dictionary)
- {
- string[] words = line.Split(' ');
- if (direction == 1)
- dict.Add(words[0], words[1]);
- else
- dict.Add(words[1], words[0]);
- }
- }
Решение задачи: «Как использовать переменную из другого метода?»
textual
Листинг программы
- private static string put = string.Empty;
- public static void Put()
- {
- put = Console.ReadLine();
- if (put == "default") put = @"Dictionary.txt";
- }
- public Translator(int direction)
- {
- string[] dictionary = File.ReadAllLines( put, Encoding.Default);
- foreach (string line in dictionary)
- {
- string[] words = line.Split(' ');
- if (direction == 1)
- dict.Add(words[0], words[1]);
- else
- dict.Add(words[1], words[0]);
- }
- }
- // строка может быть пустой? кто за кем вызывается? Оба метода точно должны быть public?
- //1 вариант. код выше можно оставить.
- public Translator(int direction)
- {
- Put();
- string[] dictionary = File.ReadAllLines( put, Encoding.Default);
- foreach (string line in dictionary)
- {
- string[] words = line.Split(' ');
- if (direction == 1)
- dict.Add(words[0], words[1]);
- else
- dict.Add(words[1], words[0]);
- }
- }
- //2 вариант. код выше не нужен.
- public static string Put()
- {
- string put = Console.ReadLine();
- if (put == "default") put = @"Dictionary.txt";
- return put;
- }
- public Translator(int direction)
- {
- string[] dictionary = File.ReadAllLines( Put(), Encoding.Default);
- foreach (string line in dictionary)
- {
- string[] words = line.Split(' ');
- if (direction == 1)
- dict.Add(words[0], words[1]);
- else
- dict.Add(words[1], words[0]);
- }
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д