Что делать, если в игре Terraria выходит ошибка: Индекс находился вне границ массива в игре? Решение было предложено несколькими способами.
Если возникает такая проблема:
System.IndexOutOfRangeException: Индекс находился вне границ массива.
в Terraria.Lang.setLang(Boolean english)
по адресу %userprofile%DocumentsMy GamesTerrariaconfig.json вместо Language=0 прописываем Language=1 или откатываем русификатор до версии 1.3.3.3_1.4.5 (GOG).
Или помогла следующая манипуляция:
Через прогу для обновления русика откатил русик до версии 1.3.3.3_1.4.5 (GOG). Игра запустилась, настроил всё, создал перса, мир, запустил мир, вышел из него и из игры. После установил снова последнюю версию русика 1.3.4.4_1.5.1. Теперь игра прекрасно запускается и работает на последнем русике.
-
#1
So I play modded Terraria and sometimes whenever I place something, for example a chandelier, it gives me this exception saying: Index out of bounds of the array. This does not happen every time I place an object, just occasionally. I checked the
logs.txt
file and it says:
Silently Caught Exception: Index was outside the bounds of the array. at Terraria.ModLoader.GlobalItem.Instance(Item item) at Terraria.ModLoader.ModCompile.<>c.<ActivateExceptionReporting>b__15_0(Object sender, FirstChanceExceptionEventArgs exceptionArgs)
at Terraria.ModLoader.GlobalItem.Instance(Item item)
at Terraria.ModLoader.ItemLoader.ConsumeItem(Item item, Player player)
at Terraria.Player.ItemCheck(Int32 i)
at Terraria.Player.ItemCheckWrapped(Int32 i)
at Terraria.Player.Update(Int32 i)
at Terraria.Main.DoUpdate(GameTime gameTime)
at Terraria.Main.Update(GameTime gameTime)
at Microsoft.Xna.Framework.Game.Tick()
at Microsoft.Xna.Framework.Game.HostIdle(Object sender, EventArgs e)
at Microsoft.Xna.Framework.GameHost.OnIdle()
at Microsoft.Xna.Framework.WindowsGameHost.RunOneFrame()
at Microsoft.Xna.Framework.WindowsGameHost.ApplicationIdle(Object sender, EventArgs e)
at System.Windows.Forms.Application.ThreadContext.System.Windows.Forms.UnsafeNativeMethods.IMsoComponent.FDoIdle(Int32 grfidlef)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at Microsoft.Xna.Framework.WindowsGameHost.Run()
at Microsoft.Xna.Framework.Game.RunGame(Boolean useBlockingRun)
at Terraria.Program.LaunchGame(String[] args, Boolean monoArgs)
at Terraria.WindowsLaunch.Main(String[] args)
I would really appreciate it if someone helped because it is really annoying when the exception pops up in the chat.
-
#2
The exception kinda states the obvious, in which it’s a problem related to items being used. Being an index out of bounds exception, it can be a huge multitude of things, which would normally be critical enough to cause a full fledged crash but it’s somehow being caught.
It would help if you shared your list of loaded mods.
-
#3
The exception kinda states the obvious, in which it’s a problem related to items being used. Being an index out of bounds exception, it can be a huge multitude of things, which would normally be critical enough to cause a full fledged crash but it’s somehow being caught.
It would help if you shared your list of loaded mods.
These are the mods that I am currently using:
- AlchemistNPC
- Auto Trash
- Base Mod
- Beyond The Forgotten Ages
- Boss Checklist
- Builder’s Toolbox
- Calamity Addon
- Calamity Mod
- Chad’s Furniture Mod
- Crystilium
- Elements Awoken
- Fargo’s Mutant Mod
- Furniture, Food and Fun
- GRealm
- JoostMod
- Luiafk
- Magic Storage
- MaxStackPlus
- Mechtransfer
- MoreAccesories+
- Project_logic
- Recipe Browser
- SacredTools
- Solutions Mod
- Spirit Mod
- The Antiaris
- The Luggage
- Thorium
- VipixToolbox
- WeaponOut
- Which Mod Is This From?
- Wildlife Mod
- Yet Another Boss Health Bar
- imkSushi’s Mod
I just added the Split Mod. Maybe, that is causing the error?
-
#4
These are the mods that I am currently using:
- AlchemistNPC
- Auto Trash
- Base Mod
- Beyond The Forgotten Ages
- Boss Checklist
- Builder’s Toolbox
- Calamity Addon
- Calamity Mod
- Chad’s Furniture Mod
- Crystilium
- Elements Awoken
- Fargo’s Mutant Mod
- Furniture, Food and Fun
- GRealm
- JoostMod
- Luiafk
- Magic Storage
- MaxStackPlus
- Mechtransfer
- MoreAccesories+
- Project_logic
- Recipe Browser
- SacredTools
- Solutions Mod
- Spirit Mod
- The Antiaris
- The Luggage
- Thorium
- VipixToolbox
- WeaponOut
- Which Mod Is This From?
- Wildlife Mod
- Yet Another Boss Health Bar
- imkSushi’s Mod
Yes, I know there are a lot. I just added the Split Mod. Maybe, that is causing the error?
Yeah which makes diagnosing the bug a whole lot of a mess.
I would suggest making a backup of your world, then turning off mods one by one in order by those that are the most likely to be affecting item using or tiles placement. This is going to likely mess up mods with modded chests or some other modded tiles, which is the point of the backup.
-
#5
Yeah which makes diagnosing the bug a whole lot of a mess.
I would suggest making a backup of your world, then turning off mods one by one in order by those that are the most likely to be affecting item using or tiles placement. This is going to likely mess up mods with modded chests or some other modded tiles, which is the point of the backup.
This will take some time.
-
#6
Yeah which makes diagnosing the bug a whole lot of a mess.
I would suggest making a backup of your world, then turning off mods one by one in order by those that are the most likely to be affecting item using or tiles placement. This is going to likely mess up mods with modded chests or some other modded tiles, which is the point of the backup.
Yes! After 1 hour of searching I finally found out what mod is causing the error. It is Sacred Tools. I reported the bug to the main developer and he said that it was a bug which they are trying to fix for a long time.
Last edited: May 30, 2018
-
#7
-
Capture.png
56.7 KB
· Views: 1,234
-
#1
So I play modded Terraria and sometimes whenever I place something, for example a chandelier, it gives me this exception saying: Index out of bounds of the array. This does not happen every time I place an object, just occasionally. I checked the
logs.txt
file and it says:
Silently Caught Exception: Index was outside the bounds of the array. at Terraria.ModLoader.GlobalItem.Instance(Item item) at Terraria.ModLoader.ModCompile.<>c.<ActivateExceptionReporting>b__15_0(Object sender, FirstChanceExceptionEventArgs exceptionArgs)
at Terraria.ModLoader.GlobalItem.Instance(Item item)
at Terraria.ModLoader.ItemLoader.ConsumeItem(Item item, Player player)
at Terraria.Player.ItemCheck(Int32 i)
at Terraria.Player.ItemCheckWrapped(Int32 i)
at Terraria.Player.Update(Int32 i)
at Terraria.Main.DoUpdate(GameTime gameTime)
at Terraria.Main.Update(GameTime gameTime)
at Microsoft.Xna.Framework.Game.Tick()
at Microsoft.Xna.Framework.Game.HostIdle(Object sender, EventArgs e)
at Microsoft.Xna.Framework.GameHost.OnIdle()
at Microsoft.Xna.Framework.WindowsGameHost.RunOneFrame()
at Microsoft.Xna.Framework.WindowsGameHost.ApplicationIdle(Object sender, EventArgs e)
at System.Windows.Forms.Application.ThreadContext.System.Windows.Forms.UnsafeNativeMethods.IMsoComponent.FDoIdle(Int32 grfidlef)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at Microsoft.Xna.Framework.WindowsGameHost.Run()
at Microsoft.Xna.Framework.Game.RunGame(Boolean useBlockingRun)
at Terraria.Program.LaunchGame(String[] args, Boolean monoArgs)
at Terraria.WindowsLaunch.Main(String[] args)
I would really appreciate it if someone helped because it is really annoying when the exception pops up in the chat.
-
#2
The exception kinda states the obvious, in which it’s a problem related to items being used. Being an index out of bounds exception, it can be a huge multitude of things, which would normally be critical enough to cause a full fledged crash but it’s somehow being caught.
It would help if you shared your list of loaded mods.
-
#3
The exception kinda states the obvious, in which it’s a problem related to items being used. Being an index out of bounds exception, it can be a huge multitude of things, which would normally be critical enough to cause a full fledged crash but it’s somehow being caught.
It would help if you shared your list of loaded mods.
These are the mods that I am currently using:
- AlchemistNPC
- Auto Trash
- Base Mod
- Beyond The Forgotten Ages
- Boss Checklist
- Builder’s Toolbox
- Calamity Addon
- Calamity Mod
- Chad’s Furniture Mod
- Crystilium
- Elements Awoken
- Fargo’s Mutant Mod
- Furniture, Food and Fun
- GRealm
- JoostMod
- Luiafk
- Magic Storage
- MaxStackPlus
- Mechtransfer
- MoreAccesories+
- Project_logic
- Recipe Browser
- SacredTools
- Solutions Mod
- Spirit Mod
- The Antiaris
- The Luggage
- Thorium
- VipixToolbox
- WeaponOut
- Which Mod Is This From?
- Wildlife Mod
- Yet Another Boss Health Bar
- imkSushi’s Mod
I just added the Split Mod. Maybe, that is causing the error?
-
#4
These are the mods that I am currently using:
- AlchemistNPC
- Auto Trash
- Base Mod
- Beyond The Forgotten Ages
- Boss Checklist
- Builder’s Toolbox
- Calamity Addon
- Calamity Mod
- Chad’s Furniture Mod
- Crystilium
- Elements Awoken
- Fargo’s Mutant Mod
- Furniture, Food and Fun
- GRealm
- JoostMod
- Luiafk
- Magic Storage
- MaxStackPlus
- Mechtransfer
- MoreAccesories+
- Project_logic
- Recipe Browser
- SacredTools
- Solutions Mod
- Spirit Mod
- The Antiaris
- The Luggage
- Thorium
- VipixToolbox
- WeaponOut
- Which Mod Is This From?
- Wildlife Mod
- Yet Another Boss Health Bar
- imkSushi’s Mod
Yes, I know there are a lot. I just added the Split Mod. Maybe, that is causing the error?
Yeah which makes diagnosing the bug a whole lot of a mess.
I would suggest making a backup of your world, then turning off mods one by one in order by those that are the most likely to be affecting item using or tiles placement. This is going to likely mess up mods with modded chests or some other modded tiles, which is the point of the backup.
-
#5
Yeah which makes diagnosing the bug a whole lot of a mess.
I would suggest making a backup of your world, then turning off mods one by one in order by those that are the most likely to be affecting item using or tiles placement. This is going to likely mess up mods with modded chests or some other modded tiles, which is the point of the backup.
This will take some time.
-
#6
Yeah which makes diagnosing the bug a whole lot of a mess.
I would suggest making a backup of your world, then turning off mods one by one in order by those that are the most likely to be affecting item using or tiles placement. This is going to likely mess up mods with modded chests or some other modded tiles, which is the point of the backup.
Yes! After 1 hour of searching I finally found out what mod is causing the error. It is Sacred Tools. I reported the bug to the main developer and he said that it was a bug which they are trying to fix for a long time.
Last edited: May 30, 2018
-
#7
can someone help me
-
Capture.png
56.7 KB
· Views: 1,107
Jiferkil 0 / 0 / 0 Регистрация: 05.01.2022 Сообщений: 26 |
||||
1 |
||||
05.03.2022, 12:39. Показов 2842. Ответов 16 Метки нет (Все метки)
Помогите решить проблему, при запуске кода меняя число строк и столбцов выдаёт в TextBox двух найденных элементов «Матрицы.Form1, Text: Матрицы», а если поставить в строках и столбцах числа больше 8 выдаёт такую ошибку <System.IndexOutOfRangeException: «Индекс находился вне границ массива.»> Написанный код:
Ошибки выдаваемые при запуске кода:
__________________ 0 |
138 / 137 / 42 Регистрация: 26.10.2012 Сообщений: 443 |
|
05.03.2022, 13:16 |
2 |
Jiferkil, для начала у вас в 10 и 11 строке один и тот же массив, переменная mas, используется. Подозреваю что это опечатка. Наступает момент когда в переменной цикла j появляется значение, которые выходит за диапазон индексов переменной mas, и вы получаете свою ошибку. 0 |
0 / 0 / 0 Регистрация: 05.01.2022 Сообщений: 26 |
|
05.03.2022, 14:28 [ТС] |
3 |
Да, был невнимателен, это была опечатка, и перепроверив, нашёл их несколько, исправив всё равно то же самое выдаёт Добавлено через 24 минуты 0 |
bite 3265 / 2853 / 659 Регистрация: 13.04.2015 Сообщений: 6,739 |
|
05.03.2022, 14:50 |
4 |
int [] mas = new int[mass.Length]; Вы понимаете, что происходит в этой строке? Добавлено через 1 минуту
исправив всё равно Какой сейчас код? 0 |
Jiferkil 0 / 0 / 0 Регистрация: 05.01.2022 Сообщений: 26 |
||||
05.03.2022, 15:18 [ТС] |
5 |
|||
0 |
138 / 137 / 42 Регистрация: 26.10.2012 Сообщений: 443 |
|
05.03.2022, 15:22 |
6 |
Jiferkil, в какой строке сейчас возникает ошибка и кто её выбрасывает? И почему у вас в 38й и 40й строках строгое условие для цикла 10 итераций? Может поэтому и проблема возникает? Замените в 38й строке 10 на mas.Length, а в 40й 10 на mad.Length 0 |
0 / 0 / 0 Регистрация: 05.01.2022 Сообщений: 26 |
|
05.03.2022, 15:55 [ТС] |
7 |
Изначально условие и было такое которое вы предлагаете, сейчас ошибка возникает в 42 строке 0 |
138 / 137 / 42 Регистрация: 26.10.2012 Сообщений: 443 |
|
05.03.2022, 15:57 |
8 |
у вас 10 проходов по циклу, вы уверены, что в циклах mas и mad есть такое количество элементов? поставьте точку останова на этой строке и в отладчике пройдитесь по каждому шагу до момента возникновения ошибки. Всё станет предельно ясно. 0 |
bite 3265 / 2853 / 659 Регистрация: 13.04.2015 Сообщений: 6,739 |
|
05.03.2022, 16:43 |
9 |
Jiferkil, какое задание вообще? 0 |
0 / 0 / 0 Регистрация: 05.01.2022 Сообщений: 26 |
|
05.03.2022, 16:49 [ТС] |
10 |
Ошибок конечно уже нет, но теперь в матрице пусто, а в найденных элементах выдаёт такой текст 0 |
bite 3265 / 2853 / 659 Регистрация: 13.04.2015 Сообщений: 6,739 |
|
05.03.2022, 17:13 |
11 |
в найденных элементах выдаёт такой текст Так ты ничего и не ищешь и ничего не выводишь. Блин, тут на 10 минут делов. Какое задание? Добавлено через 21 минуту 0 |
138 / 137 / 42 Регистрация: 26.10.2012 Сообщений: 443 |
|
05.03.2022, 21:45 |
12 |
Jiferkil, скажи что требуется в твоей программе, быстрее поможем. 1 |
0 / 0 / 0 Регистрация: 05.01.2022 Сообщений: 26 |
|
06.03.2022, 08:11 [ТС] |
13 |
Составить программу, предусматривающую использование компонентов класса DataGridView для ввода или вывода матриц/массивов. Задание размеров матриц/массивов с осуществлять с помощью компонентов класса NumericUpDown. 0 |
bite 3265 / 2853 / 659 Регистрация: 13.04.2015 Сообщений: 6,739 |
|
06.03.2022, 08:49 |
14 |
Jiferkil, ну вот, теперь понятно. Ты же всё неправильно сделал. Сейчас набросаю. 0 |
0 / 0 / 0 Регистрация: 05.01.2022 Сообщений: 26 |
|
06.03.2022, 08:52 [ТС] |
15 |
Просто я только-только учусь программированию на C#, а до этого особо этим не занимался, поэтому заранее извиняюсь что не вижу очевидного и большое спасибо 0 |
I can bite 3265 / 2853 / 659 Регистрация: 13.04.2015 Сообщений: 6,739 |
||||
06.03.2022, 08:59 |
16 |
|||
Сообщение было отмечено Jiferkil как решение РешениеПримерно так
Миниатюры
2 |
bite 3265 / 2853 / 659 Регистрация: 13.04.2015 Сообщений: 6,739 |
|
06.03.2022, 09:12 |
17 |
Сообщение было отмечено Jiferkil как решение РешениеПроект 2 |
Как сказали ранее, проблема находится в строке: for (int i = 0; i <= n; i++)
.
Для решения этой проблемы я бы подошел немного с другой стороны. Во время перебора коллекции можно использовать не сторонние переменные, которые могут быть ошибочными, а длину массива. Вы в первом for
использовали это.
К примеру, если n = 10
, а в массиве у Вас будет девять элементов, то Вы снова получите исключение. Вдруг переменная n
где-то поменялась?
Можно использовать Length
(для списков Count
). Вот так:
for (int index = 0; index < arr.Length; index++) {...} // в случае с массивом
for (int index = 0; index < lst.Count; index++) {...} // в случае со списком
Также очень удобен метод foreach, in для перебора коолекции, если Вам не нужны индексы, в таком случае Вам не нужно беспокоиться о знании количества элементов массива:
foreach (var item in array) {...}
Однако его не следует использовать для добавления или удаления элементов исходной коллекции во избежание непредвиденных побочных эффектов. Если нужно добавить или удалить элементы исходной коллекции, следует использовать цикл for.
С foreach
немного проще, так как он работает для массивов или коллекций объектов, реализующих интерфейс IEnumerable
или IEnumerable<T>
из System.Collections.Generic
.
Но и это еще не всё, что может облегчить работу программисту, также имеется метод Enumerable.Sum, который вычисляет сумму последовательности. И Вам не придется перебирать все элементы коллекции. К примеру:
double sum = a.Sum(); // сумма элементов Вашего массива
Также можно отметить метод Enumerable.Aggregate, который применяет к последовательности агрегатную функцию. К примеру, получение суммы будет таким:
double sum = a.Aggregate((result, item) => result + item);
- Remove From My Forums
Ошибка: Индекс находится вне границ массива
-
Вопрос
-
private string getServerName(string ip) { //Преобразуем ИП:ПОРТ в массив
string [] split = ip.Split(new Char [] {':'}); //Получаем инфо о сервере System.Net.WebRequest reqGET = System.Net.WebRequest.Create(@"http://localhost/alex/get_name.php?server=" + split[0] + "&port=" + split[1]); System.Net.WebResponse resp = reqGET.GetResponse(); System.IO.Stream stream = resp.GetResponseStream(); System.IO.StreamReader sr = new System.IO.StreamReader(stream); string s = sr.ReadToEnd(); return s; }
И во время запуска вылетает ошибка о том, что «Индекс находился вне границ массива.» Массив из 2-х элементов, я обращаюсь к 0 и 1. В чем ошибка? Прошу не судить строго и объяснить, я только изучаю все это.
- Изменено
15 августа 2014 г. 21:33
- Перемещено
YatajgaModerator
16 августа 2014 г. 17:00
- Изменено
Ответы
-
Поставьте точку остановки на строке вызова Split (поставить текстовый курсор на строку и нажать F9). Запустить отладку (F5). Программа остановится на данной строке. Сделать шаг с обходом (F10). В окне отладчика «Видимые» или «Локальные» найти массив и
проанализировать его содержимое.
Если сообщение помогло Вам, пожалуйста, не забудьте отметить его как ответ данной темы. Удачи в программировании!
- Помечено в качестве ответа
AlexUkr96
16 августа 2014 г. 10:24
- Помечено в качестве ответа
public static int FindSignature() { int[] signature = { 0xCD, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xF4, 0x3F, 0x01, 0x00, 0x00, 0x00, 0xA0, 0xB7, 0x1F, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2C, 0x40 }; long MaxAddress = 0x7fffffff; long address = 0; MEMORY_BASIC_INFORMATION m; var handle = OpenProcess(0x001F0FFF, false, GetProcessID()); m.BaseAddress = IntPtr.Zero; m.RegionSize = IntPtr.Zero; byte[] buffer; while (address <= MaxAddress) { VirtualQueryEx(handle, (IntPtr)address, out m, (uint)Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION))); buffer = new byte[(uint)m.RegionSize]; int dammy = 0; ReadProcessMemory(handle, m.BaseAddress, buffer, (int)m.RegionSize, out dammy); if (address == (long)m.BaseAddress + (long)m.RegionSize) break; int count = 0; address = (long)m.BaseAddress + (long)m.RegionSize; if (buffer.Length > signature.Length) { for (int i = 0; i < buffer.Length; i++) { if (buffer[i] == signature[0]) { for (int q = 0; q < signature.Length; q++ ) { if (buffer[i + q ] == signature[q] && signature[q] != -1) //&& signature[q] != 0 добавить в скобку выше если что-то не так { count++; if (count == signature.Length) { Func func = new Func(); var result = i + (int)m.BaseAddress; func.vamaddr += result; Func.addr = result; string some = result.ToString(); MessageBox.Show(result.ToString()); return i + (int)m.BaseAddress; } } else { count = 0; } } } } } } CloseHandle(handle); return -1; }
My world was failing to load through the main game, so I tried loading it up in the editor. Crash at load, with an invalid index. Sometimes the editor does not crash, but it doesn’t load the map either — it appears as if nothing was loaded.
Here’s a rar of all my game files — you have to click the download button at top center of screen:
https://drive.google.com/file/d/0B0mEATLjiXBXX3hKZUFDbTY0TEE/view?usp=sharing
10-19-2014 21:55: Starting TEdit 3.5.14267.29
10-19-2014 21:55: OS: Microsoft Windows NT 6.2.9200.0
10-19-2014 21:55: .Net >= 4.0
10-19-2014 21:55: XNA 4.0
10-19-2014 21:55: Terraria Data Path: E:Program Files (x86)SteamsteamappscommonTerrariaContent
10-19-2014 21:55: Creating Undo cache: C:Users[hidden]AppDataRoamingTEditundo_319387175
10-19-2014 21:55: Error - Index was outside the bounds of the array.
at TEditXna.ViewModel.WorldViewModel.MouseUpTile(TileMouseState e)
at TEditXna.View.WorldRenderXna.xnaViewport_HwndLButtonUp(Object sender, HwndMouseEventArgs e)
at TEdit.UI.Xaml.XnaContentHost.GraphicsDeviceControl.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at System.Windows.Interop.HwndHost.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.Run()
at System.Windows.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run(Window window)
at TEditXna.App.Main()
Как сказали ранее, проблема находится в строке: for (int i = 0; i <= n; i++)
.
Для решения этой проблемы я бы подошел немного с другой стороны. Во время перебора коллекции можно использовать не сторонние переменные, которые могут быть ошибочными, а длину массива. Вы в первом for
использовали это.
К примеру, если n = 10
, а в массиве у Вас будет девять элементов, то Вы снова получите исключение. Вдруг переменная n
где-то поменялась?
Можно использовать Length
(для списков Count
). Вот так:
for (int index = 0; index < arr.Length; index++) {...} // в случае с массивом
for (int index = 0; index < lst.Count; index++) {...} // в случае со списком
Также очень удобен метод foreach, in для перебора коолекции, если Вам не нужны индексы, в таком случае Вам не нужно беспокоиться о знании количества элементов массива:
foreach (var item in array) {...}
Однако его не следует использовать для добавления или удаления элементов исходной коллекции во избежание непредвиденных побочных эффектов. Если нужно добавить или удалить элементы исходной коллекции, следует использовать цикл for.
С foreach
немного проще, так как он работает для массивов или коллекций объектов, реализующих интерфейс IEnumerable
или IEnumerable<T>
из System.Collections.Generic
.
Но и это еще не всё, что может облегчить работу программисту, также имеется метод Enumerable.Sum, который вычисляет сумму последовательности. И Вам не придется перебирать все элементы коллекции. К примеру:
double sum = a.Sum(); // сумма элементов Вашего массива
Также можно отметить метод Enumerable.Aggregate, который применяет к последовательности агрегатную функцию. К примеру, получение суммы будет таким:
double sum = a.Aggregate((result, item) => result + item);