Форум программистов, компьютерный форум, киберфорум
C# для начинающих
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.76/25: Рейтинг темы: голосов - 25, средняя оценка - 4.76
1 / 1 / 1
Регистрация: 12.11.2017
Сообщений: 82
1

Не существуют имена в текущем контексте

30.11.2018, 09:35. Показов 5250. Ответов 2
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Как исправить имя Thread и Debug не существует в текущем контексте
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ConsoleApplication1
{
    class Program
    {
 
        public static T ReadValueFromConsole<T>(string message)
        {
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine(message);
            Console.ForegroundColor = ConsoleColor.White;
            while (true)
            {
                try
                {
                    return (T)Convert.ChangeType(Console.ReadLine(), typeof(T));
                }
                catch (Exception)
                {
                    Console.WriteLine("Возникла ошибка. Повторите ввод");
                }
            }
 
        }
 
        static void Main(string[] args)
        {
            ActivateMenu();
        }
 
        private static void ActivateMenu()
        {
            var alph = /*ReadValueFromConsole<string>("Введите алфавит");*/
                       // АБВГДЕЖЗИКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ
            "АБВГДЕЖЗИКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ";
 
            var key = ReadValueFromConsole<string>("\nВведите ключевое слово");
            // ТОВАРИЩ
            //"ТОВАРИЩ";
 
            var pc = new PlayfairCipher(alph, key);
            bool active = true;
            while (active)
            {
                Console.Clear();
                var choise = ReadValueFromConsole<int>(@"Выберите действие:
1. Зашифровать указанную строку
2. Десшифровать указанную строку
3. THERE IS NO ESCAPE");
                switch (choise)
                {
                    case 1:
                        Console.Clear();
                        Console.Write("Шифрование строки.");
                        var normalMessage = ReadValueFromConsole<string>("\nВведите строку для шифрования: ");
                        // КОД ПЛЕЙФЕЙЕРА ОСНОВАН НА ИСПОЛЬЗОВАНИИ МАТРИЦЫ БУКВ
                        // "КОД ПЛЕЙФЕЙЕРА ОСНОВАН НА ИСПОЛЬЗОВАНИИ МАТРИЦЫ БУКВ";
                        var crypted = pc.Crypt(normalMessage);
                        Console.WriteLine("\nResult: " + crypted);
                        Console.WriteLine("De-crypted back: " + pc.Uncrypt(crypted));
                        Console.ReadKey();
                        break;
                    case 2:
                        Console.Clear();
                        Console.Write("Дешифрование строки.");
                        var cryptedMessage = ReadValueFromConsole<string>("\nВведите строку для дешифровки: ");
                        // МОЩЕЯВЧЪЛТАПЯВМОМРЗФИЫПТБКВИХБЦБЩШЪЧШЩИВТЧОАДХОПАБТИВАРМЖИ
                        //"МОЩЕЯВЧЪЛТАПЯВМОМРЗФИЫПТБКВИХБЦБЩШЪЧШЩИВТЧОАДХОПАБТИВАРМЖИ";
                        var normal = pc.Uncrypt(cryptedMessage);
                        Console.WriteLine("\nResult: " + normal);
                        Console.WriteLine("Crypted back: " + pc.Crypt(normal));
                        Console.ReadKey();
                        break;
                    case 3:
                        active = new Random().Next(3) != 0;
                        if (!active)
                        {
                            Console.WriteLine("Lucky One");
                            Thread.Sleep(2 * 1000);
                        }
                        break;
                    default:
                        break;
                }
            }
 
        }
 
    }
 
    class PlayfairCipher
    {
        string Alphabet { get; set; }
        string KeyWord { get; set; }
        public PlayfairCipher(string Alphabet, string KeyWord)
        {
            this.KeyWord = string.Join("",
                KeyWord.ToLower()
                .Replace("й", "и")
                .Replace("ё", "е")
                .Replace("ъ", "ь")
                .Replace(" ", "")
                .Distinct());
 
            this.Alphabet = Alphabet.ToLower()
                .Replace("й", "")
                .Replace("ё", "")
                .Replace(" ", "")
                .Replace("ь", "");
        }
 
        public string Crypt(string Message)
        {
            Func<string[,], int[], int[], string> getPair = GetPairForCrypt;
 
            return CryptOrUncrypt(Message, getPair);
        }
 
        public string Uncrypt(string Message)
        {
            Func<string[,], int[], int[], string> getPair = GetPairForUncrypt;
 
            return CryptOrUncrypt(Message, getPair);
        }
 
        string CryptOrUncrypt(string Message, Func<string[,], int[], int[], string> GetPair)
        {
            var alphMatrix = CreateAlphMatrix();
            var bigrams = CreateBigrams(Message);
 
            var returnMessage = "";
 
            var fIndex = new int[] { 0, 0 };
            var sIndex = new int[] { 0, 0 };
 
            foreach (var bi in bigrams)
            {
                fIndex = GetIndex(alphMatrix, bi.FirstLetter);
                sIndex = GetIndex(alphMatrix, bi.SecondLetter);
 
                returnMessage += GetPair(alphMatrix, fIndex, sIndex);
            }
 
            return returnMessage;
        }
        string GetPairForUncrypt(string[,] AplhMatrix, int[] FirstLetterIndexs, int[] SecondLetterIndexs)
        {
            string pair = "";
 
            if (FirstLetterIndexs[0] == SecondLetterIndexs[0])
            {
                pair += AplhMatrix[
                    FirstLetterIndexs[0],
                      ((FirstLetterIndexs[1] - 1 + AplhMatrix.GetLength(1)) % AplhMatrix.GetLength(1))];
 
                pair += AplhMatrix[
                    SecondLetterIndexs[0],
                      ((SecondLetterIndexs[1] - 1 + AplhMatrix.GetLength(1)) % AplhMatrix.GetLength(1))];
            }
            // В одном столбце
            else if (FirstLetterIndexs[1] == SecondLetterIndexs[1])
            {
                pair += AplhMatrix[
                 ((FirstLetterIndexs[0] - 1 + AplhMatrix.GetLength(0)) % AplhMatrix.GetLength(0)),
                    FirstLetterIndexs[1]];
 
 
                pair += AplhMatrix[
                ((SecondLetterIndexs[0] - 1 + AplhMatrix.GetLength(0)) % AplhMatrix.GetLength(0)),
                    SecondLetterIndexs[1]];
            }
            // В одном блое
            else
            {
                pair += AplhMatrix[
                   FirstLetterIndexs[0],
                   SecondLetterIndexs[1]];
 
                pair += AplhMatrix[
                    SecondLetterIndexs[0],
                    FirstLetterIndexs[1]];
            }
 
            return pair;
        }
        string GetPairForCrypt(string[,] AplhMatrix, int[] FirstLetterIndexs, int[] SecondLetterIndexs)
        {
            string pair = "";
 
            if (FirstLetterIndexs[0] == SecondLetterIndexs[0])
            {
                pair += AplhMatrix[
                 FirstLetterIndexs[0],
                   ((FirstLetterIndexs[1] + 1) % AplhMatrix.GetLength(1))];
 
                pair += AplhMatrix[
                    SecondLetterIndexs[0],
                      ((SecondLetterIndexs[1] + 1) % AplhMatrix.GetLength(1))];
            }
 
            // В одном столбце
            else if (FirstLetterIndexs[1] == SecondLetterIndexs[1])
            {
                pair += AplhMatrix[
                 ((FirstLetterIndexs[0] + 1) % AplhMatrix.GetLength(0)),
                    FirstLetterIndexs[1]];
 
                pair += AplhMatrix[
                ((SecondLetterIndexs[0] + 1) % AplhMatrix.GetLength(0)),
                    SecondLetterIndexs[1]];
            }
 
            // В одном блоке
            else
            {
                pair += AplhMatrix[
                   FirstLetterIndexs[0],
                   SecondLetterIndexs[1]];
 
                pair += AplhMatrix[
                    SecondLetterIndexs[0],
                    FirstLetterIndexs[1]];
            }
 
            return pair;
        }
        int[] GetIndex(string[,] matrix, string Letter)
        {
            for (int i = 0; i < matrix.GetLength(0); i++)
            {
                for (int j = 0; j < matrix.GetLength(1); j++)
                {
                    if (matrix[i, j] == Letter)
                        return new int[] { i, j };
                }
            }
            throw new Exception();
        }
 
        IEnumerable<Bigram> CreateBigrams(string normalMessage)
        {
            normalMessage = normalMessage.ToLower()
                .Replace("й", "и")
                .Replace("ё", "е")
                .Replace("ь", "ъ")
                .Replace(" ", "");
            var temp = new List<Bigram>();
 
            for (int i = 0; i < normalMessage.Length; i += 2)
            {
                if (i == normalMessage.Length - 1)
                {
                    temp.Add(new Bigram()
                    {
                        FirstLetter = normalMessage[i].ToString(),
                        SecondLetter = "х"
                    });
                }
                else if (normalMessage[i] == normalMessage[i + 1])
                {
                    temp.Add(new Bigram()
                    {
                        FirstLetter = normalMessage[i].ToString(),
                        SecondLetter = "х"
                    });
                    i--;
                }
                else
                {
                    temp.Add(new Bigram()
                    {
                        FirstLetter = normalMessage[i].ToString(),
                        SecondLetter = normalMessage[i + 1].ToString()
                    });
                }
            }
 
            return temp;
        }
        string[,] CreateAlphMatrix()
        {
            var let = (KeyWord + Alphabet).Select(x => x.ToString()).Distinct().ToArray();
 
            var alphMatrix = new string[5, 6];
 
            var temp_index = 0;
 
            Debug.WriteLine("New alphabet:");
 
            for (int i = 0; i < alphMatrix.GetLength(0); i++)
            {
                for (int j = 0; j < alphMatrix.GetLength(1); j++)
                {
                    alphMatrix[i, j] = let[temp_index];
                    Debug.Write(alphMatrix[i, j] + " ");
                    temp_index++;
                }
                Debug.WriteLine("");
            }
 
            return alphMatrix;
        }
 
        class Bigram
        {
            public string FirstLetter { get; set; }
            public string SecondLetter { get; set; }
 
            public override string ToString()
            {
                return FirstLetter + " " + SecondLetter;
            }
        }
    }
 
}
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
30.11.2018, 09:35
Ответы с готовыми решениями:

Ошибка "имена не существуют в текущем контексте" при вызове конструктора базового класса
ошибка в base(title, produce, form) (produce, form не существуют в текущем контексте) class...

Классы. Ошибка "Имена не существуют в данном контексте"
Мне нужно создать объект определённого класса. Взял код у друга для примера: using System; using...

Не существует в текущем контексте
private void createIncAndOut() { if (E.Count &gt; 0) { ...

Имя не существует в текущем контексте
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data;...

2
910 / 795 / 329
Регистрация: 08.02.2014
Сообщений: 2,391
30.11.2018, 10:09 2
Лучший ответ Сообщение было отмечено Ivan2117 как решение

Решение

Цитата Сообщение от Ivan2117 Посмотреть сообщение
Как исправить имя Thread и Debug не существует в текущем контексте
добавь
C#
1
2
using System.Diagnostics;
using System.Threading;
1
15 / 11 / 5
Регистрация: 20.03.2014
Сообщений: 151
30.11.2018, 10:21 3
Лучший ответ Сообщение было отмечено Ivan2117 как решение

Решение

Цитата Сообщение от Ivan2117 Посмотреть сообщение
Как исправить имя Thread и Debug не существует в текущем контексте
При возникновении подобной ошибки студия предлагает возможные варианты решений.


Просто наведи указателем мыши на подчеркнутую строку.
Синим цветом в выпадающем меню "Показать возможные решения"
Добавления using там будет первым пунктом.

Не существуют имена в текущем контексте
1
30.11.2018, 10:21
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
30.11.2018, 10:21
Помогаю со студенческими работами здесь

Элемент не существует в текущем контексте
Решил выделить код в отдельный класс - новый класс Visual Studio наотрез отказывается видеть. ...

Переменная не существует в текущем контексте
Здравствуйте! У меня возникла небольшая проблема. При нажатии на кнопку у меня вычисляется значение...

Url не существует в текущем контексте
Контроллер using System; using System.Collections.Generic; using System.Linq; using...

Assert - не существует в текущем контексте
Здравствуйте. Пробую добавить Microsoft.VisualStudio.TestTools.UnitTesting - но и здесь...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru