Я совершенно запутался. Моя программа сбивается с ошибкой исключений. Просмотр просмотра событий Windows перечисляет ошибку выполнения .NET следующим образом: < /p>
Application: modifyMap.exe
CoreCLR Version: 8.0.1525.16413
.NET Version: 8.0.15
Description: The process was terminated due to an unhandled exception.
Exception Info: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: No overload for method 'this' takes 2 arguments
at CallSite.Target(Closure, CallSite, Object, Int32, Int32)
at System.Dynamic.UpdateDelegates.UpdateAndExecute3[T0,T1,T2,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2)
at ModifyTest.Program.printMap(Location[,] map, String mapType, Object coords) in C:\Users\aaron\OneDrive\Desktop\modifyMap\Program.cs:line 520
at ModifyTest.Program.getCoords(Location[,] map, List`1 changedCoords) in C:\Users\aaron\OneDrive\Desktop\modifyMap\Program.cs:line 285
at ModifyTest.Program.modifyMap() in C:\Users\aaron\OneDrive\Desktop\modifyMap\Program.cs:line 26
at ModifyTest.Program.Main() in C:\Users\aaron\OneDrive\Desktop\modifyMap\Program.cs:line 12
< /code>
Это строка 520, где происходит ошибка: < /p>
Console.WriteLine($"COORD NOT FOUND: {coords[i, j]}\n");
< /code>
Насколько мне известно, единственная консоль аргумента. В этом случае форматированная строка. И координат [i, j] является элементом int [] в списке of Length
Я не вижу ничего необычного, что не должно было выставить здесь ошибку. Я понятия не имею, почему это будет бросать эту конкретную ошибку на эту линию. И, честно говоря, я не знаю, какие еще детали предложить, чтобы помочь, так что здесь большая часть кода. < /P>
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
namespace ModifyTest
{
public class Program
{
public static void Main()
{
modifyMap();
}
static void modifyMap()
{
// TEST MAP
// MainFunctions funcs = new MainFunctions();
Location[,] map = MainFunctions.generateMap();
// TRACK COORDINATES HAVE ALREADY BEEN CHANGED
List changedCoords = new List();
// FOR BOSS LOCATION TEST. ACQUIRED FROM ARGUMENTS, NOT TO BE INCLUDED IN FINAL FUNCTION
// List coords = new List { new int[] { 1, 2 }, new int[] { 3, 4 }, new int[] { 5, 6 } };
List coords = getCoords(map, changedCoords);
Random randInt = new Random();
// GLOBAL: Question/answer readout string
string readout = "";
// Take user provided parameters until user commits changes
bool commit = false;
do
{
// type == AREA TYPE (distantDesc, closeDesc assigned at target iteration)
// string typeQuestion = "ENTER AREA TYPE: ";
string typeAnswer;
string[] acceptableTypes = new string[] {
"Resistance Base",
"Scrapyard",
"Ruined Hospital",
"Bombed Building",
"Wasteland",
"HK-VTOL",
"HK-TANK",
"Harvester"
};
do
{
Console.Clear();
Console.Write(readout);
Console.Write("ENTER AREA TYPE: ");
typeAnswer = Console.ReadLine();
typeAnswer = correctString(typeAnswer);
} while (!acceptableTypes.Contains(typeAnswer));
readout += $"ENTER AREA TYPE: {typeAnswer}\n";
// Only one of each boss type permitted per location. Notify of restriction and relocation.
if (coords.Count > 1 && new string[] { "HK-VTOL", "HK-TANK", "Harvester" }.Contains(typeAnswer))
{
readout += $"\nWARNING: Only one {typeAnswer} is permitted per map. {typeAnswer} will be relocated to first coordinate listed.\nOther coordinates will be discarded.\n\n";
}
// Record area boolean values
bool t600Answer, t800Answer, visitedAnswer, recruitedAnswer, healthPackAnswer, upgradeAnswer, trapAnswer, trapActiveAnswer, transportAnswer;
// hasVisited -- DETERMINES IF AREA HAS BEEN VISITED BY JOHN CONNOR
visitedAnswer = getYesOrNo(readout, "HAS JOHN CONNOR VISITED OR SCOUTED THIS LOCATION: ");
readout += "HAS JOHN CONNOR VISITED OR SCOUTED THIS LOCATION: " + (visitedAnswer ? "YES" : "NO") + "\n";
// ONLY ENEMIES AND TRANSPORTS AVAILABLE AT WASTELANDS
if (typeAnswer == "Wasteland")
{
recruitedAnswer = healthPackAnswer = upgradeAnswer = trapAnswer = trapActiveAnswer = false;
// isT600 -- T-600 PRESENCE
t600Answer = getYesOrNo(readout, "T-600 PRESENT: ");
readout += "T-600 PRESENT: " + (t600Answer ? "YES" : "NO") + "\n";
// isT800 -- T-800 PRESENCE, T-600 PRESENCE NEGATED IF T-800 PRESENT
t800Answer = getYesOrNo(readout, "T-800 PRESENT ('YES' WILL REMOVE T-600): ");
if (t600Answer && t800Answer)
{
t600Answer = false;
readout = readout.Replace("T-600 PRESENT: YES\n", "T-600 PRESENT: NO\n");
}
readout += "T-800 PRESENT ('YES' WILL REMOVE T-600): " + (t800Answer ? "YES" : "NO") + "\n";
// isTransport -- DETERMINES IF TRANSPORTATION IS PRESENT, ONLY AVAILABLE AT WASTELANDS
transportAnswer = getYesOrNo(readout, "TRANSPORT PRESENT: ");
readout += "TRANSPORT PRESENT: " + (transportAnswer ? "YES" : "NO") + "\n";
}
else
{
// hasRecruited -- IF TYPE IS RESISTANCE BASE, DETERMINES IS SOLDIER CAN BE RECRUITED HERE
if (typeAnswer == "Resistance Base" && visitedAnswer)
{
recruitedAnswer = getYesOrNo(readout, "HAS JOHN CONNOR RECRUITED FROM THIS BASE: ");
readout += "HAS JOHN CONNOR RECRUITED FROM THIS BASE: " + (recruitedAnswer ? "YES" : "NO") + "\n";
}
else
{
recruitedAnswer = false;
}
// IF TYPE IS NEITHER A BOSS LOCATION OR A RESISTANCE BASE...
bool bossOrBase = new string[] { "Resistance Base", "HK-TANK", "HK-VTOL", "Harvester" }.Contains(
typeAnswer);
if (!bossOrBase)
{
// isT600 -- T-600 PRESENCE
t600Answer = getYesOrNo(readout, "T-600 PRESENT: ");
readout += "T-600 PRESENT: " + (t600Answer ? "YES" : "NO") + "\n";
// isT800 -- T-800 PRESENCE, T-600 PRESENCE NEGATED IF T-800 PRESENT
t800Answer = getYesOrNo(readout, "T-800 PRESENT ('YES' WILL REMOVE T-600): ");
if (t600Answer && t800Answer)
{
t600Answer = false;
readout = readout.Replace("T-600 PRESENT: YES\n", "T-600 PRESENT: NO\n");
}
readout += "T-800 PRESENT ('YES' WILL REMOVE T-600): " + (t800Answer ? "YES" : "NO") + "\n";
// isHealthPack -- HEALTH PACK PRESENCE
healthPackAnswer = getYesOrNo(readout, "HEALTH PACK PRESENT: ");
readout += "HEALTH PACK PRESENT: " + (healthPackAnswer ? "YES" : "NO") + "\n";
}
else
{
t600Answer = t800Answer = healthPackAnswer = false;
}
// IF TYPE IS SCRAPYARD...
if (typeAnswer == "Scrapyard")
{
// isUpgrade -- DETERMINES UPGRADE PRESENCE
upgradeAnswer = getYesOrNo(readout, "UPGRADE PRESENT: ");
readout += "UPGRADE PRESENT: " + (upgradeAnswer ? "YES" : "NO") + "\n";
// isTermTrap -- DETERMINES TERMINATOR TRAP PRESENCE
trapAnswer = getYesOrNo(readout, "TRAP PRESENT: ");
readout += "TRAP PRESENT: " + (trapAnswer ? "YES" : "NO") + "\n";
// isTermTrapActive -- IF TRAP PRESENT, DETERMINES IF TRAP IS ACTIVE
if (trapAnswer)
{
trapActiveAnswer = getYesOrNo(readout, "TRAP ACTIVE: ");
readout += "TRAP ACTIVE: " + (trapActiveAnswer ? "YES" : "NO") + "\n";
}
else
{
trapActiveAnswer = false;
}
}
else
{
upgradeAnswer = trapAnswer = trapActiveAnswer = false;
}
// isTransport -- DETERMINES IF TRANSPORTATION IS PRESENT, ONLY AVAILABLE AT WASTELANDS
transportAnswer = false;
}
// Ask to commit changes, repeat loop if user declines
bool doCommit = false;
doCommit = getYesOrNo(readout, "\nCOMMIT THESE CHANGES? : ");
if (doCommit)
{
// ----------- ITERATE COORDS, CHANGE MAP LOCOATION PROPERTIES ----------- //
/*
CHANGE VARIABLES:
string typeAnswer;
bool t600Answer, t800answer, visitedAnswer, recruitedAnswer, healthPackAnswer, upgradeAnswer, trapAnswer, trapActiveAnswer, transportAnswer;
PROPERTIES TO BE CHANGED:
(Location).
type, isT600, isT800, hasVisited, hasRecruited, isHealthPack, isUpgrade, isTermTrap, isTermTrapActive, isTransport
*/
// Notify of boss relocation, truncate coordinate list to first element, swap location values
bool coordsTooLong = coords.Count > 1;
if (new string[] { "HK-TANK", "HK-VTOL", "Harvester" }.Contains(
typeAnswer))
{
coords.RemoveRange(1, coords.Count - 1);
Console.WriteLine($"\n{typeAnswer} relocated from ({"OLD LOCATION"}) to ({coords[0][0]},{coords[0][1]}){(coordsTooLong ? " per truncated coordinate list." : ".")}\nCoordinate ({coords[0][0]},{coords[0][1]}) previous designation and properties will be transferred to previous \n{typeAnswer} location: ({"OLD LOCATION"})");
Console.WriteLine("\n-- RELOCATE HERE. REPLACE OLD LOCATION WITH CURRENT LOCATION TYPE AND VALUES --");
}
// CONTINUE AREA PROPERTIES ASSIGNMENT HERE...
// ----------- ITERATE COORDS, CHANGE MAP LOCOATION PROPERTIES ----------- //
Console.Write($"\nLOCATION{(coords.Count > 1 ? "S" : "")} --");
foreach (int[] coord in coords)
Console.Write($" ({coord[0]},{coord[1]}) ");
Console.WriteLine($"-- {(coords.Count > 1 ? "HAVE" : "HAS")} BEEN DESIGNATED \"{typeAnswer}\" AND GIVEN THE FOLLOWING PROPERTIES:\n");
Console.WriteLine($"TYPE: {typeAnswer}");
Console.WriteLine($"T-600: {t600Answer}");
Console.WriteLine($"T-800: {t800Answer}");
Console.WriteLine($"VISITED: {visitedAnswer}");
Console.WriteLine($"RECRUITED: {recruitedAnswer}");
Console.WriteLine($"HEALTH PACK: {healthPackAnswer}");
Console.WriteLine($"UPGRADE: {upgradeAnswer}");
Console.WriteLine($"TRAP: {trapAnswer}");
Console.WriteLine($"TRAP ACTIVE: {trapActiveAnswer}");
Console.WriteLine($"TRANSPORT: {transportAnswer}");
// --------------------------- //
commit = true;
// Press any key to continue
Console.Write("\n\nPRESS ANY KEY TO CONTINUE: ");
Console.ReadKey(true);
if (Console.KeyAvailable) { }
;
}
} while (!commit);
}
// GET YES OR NO ANSWER FUNCTION
static bool getYesOrNo(string readout, string question)
{
string answer;
string[] acceptableAnswers = new string[] { "YES", "Y", "NO", "N" };
do
{
Console.Clear();
Console.Write(readout);
Console.Write(question);
answer = Console.ReadLine();
} while (!acceptableAnswers.Contains(answer.ToUpper()));
return new string[] { "YES", "Y" }.Contains(answer.ToUpper()) ? true : false;
}
// CORRECT AREA TYPE STRING FUNCTION
static string correctString(string answer)
{
if (answer.ToUpper() == "HK-TANK" || answer.ToUpper() == "HK-VTOL")
return answer.ToUpper();
string newString = "";
// Correct answer string, each word capitalized
bool upper = true;
for (int i = 0; i < answer.Length; i++)
{
if (upper)
{
newString += answer.ToString().ToUpper();
upper = false;
}
else
{
if (answer.ToString() == " ")
upper = true;
newString += answer.ToString().ToLower();
}
}
return newString;
}
// GET USER INPUT FOR COORDINATES, RETURN OF { [-1, -1] } INDICATES "QUIT", RETURN OF { [-2, -2] } INDICATES ERROR
static dynamic getCoords(Location[,] map, List changedCoords)
{
// Modification choice
string choice;
do
{
Console.Clear();
// Print area map
printMap(map, "complete");
// Prompt for area selection method
Console.Write("1) Select all areas of a specific type\n2) Provide area list\n\nENTER CHOICE ('X' to cancel): ");
choice = Console.ReadLine().ToUpper();
} while (!new string[] { "1", "2", "X" }.Contains(choice));
// If user chooses to quit, return {-1, -1} to signify
if (choice == "X")
return "QUIT";
if (choice == "1") // By area type
{
string areaType;
string[] acceptableTypes = new string[] {
"WASTELAND",
"RESISTANCE BASE",
"RUINED HOSPITAL",
"BOMBED BUILDING",
"SCRAPYARD",
};
string[] bossTypes = new string[]
{
"HK-TANK",
"HK-VTOL",
"HARVESTER"
};
do
{
Console.Clear();
printMap(map, "complete");
Console.Write("ENTER AREA TYPE: ");
areaType = Console.ReadLine().ToUpper();
if (bossTypes.Contains(areaType))
{
Console.Clear();
printMap(map, "complete");
Console.Write("INVALID INPUT: Boss types must be relocated individually.\nPRESS ANY KEY TO CONTINUE: ");
// Press any key to continue
Console.ReadKey(true);
if (Console.KeyAvailable) { };
}
} while (!acceptableTypes.Contains(areaType));
// Collect location targets by specified area type, return targets
List areaCoords = new List();
for (int i = 0; i < map.GetLength(0); i++)
{
for (int j = 0; j < map.GetLength(1); j++)
{
if (map[i,j].type == areaType)
{
areaCoords.Add(new int[] { i, j });
}
}
}
return areaCoords;
}
else if (choice == "2") // By coordinate list
{
// Collect coordinate pairs as string
string coordString;
bool coordStringValid = true;
// Store coordinate pairs
List coords = new List();
// Collect coordinate string, reject invalid strings
do
{
coordStringValid = true;
// Get user input
Console.Write("List areas to modify (#,# ...), or type 'X' to quit: ");
coordString = Console.ReadLine().ToUpper();
// Check if user wishes to cancel the change
if (coordString == "X") return "QUIT";
// Ensure all characters in string are valid, reject if invalid character is found
foreach (char letter in coordString)
{
if (!"0123456789, ".Contains(letter))
{
coordStringValid = false;
break;
}
}
if (!coordStringValid) continue;
// Iterate and parse provided coordinates. If coordinate is out of bounds, break and clear parsed coordinates
// Populate coordinates list
string[] coordPairs = coordString.Split(' ');
// Check that each coordinate pair contains only two integers, accounting for ',' delimiter (#,#)
foreach (string coord in coordPairs)
{
if (coord.Length != 3)
{
coordStringValid = false;
break;
}
}
if (!coordStringValid) continue;
// Parse, evaluate, and add coordinates to list
foreach (string pair in coordPairs)
{
string[] pairNums = pair.Split(',');
int pair1 = Int32.Parse(pairNums[0]);
int pair2 = Int32.Parse(pairNums[1]);
// If past changed area is re-targeted in current selection, remove from changed coordinates
if (changedCoords.Count > 0)
{
for (int i = 0; i < changedCoords.Count; i++)
{
if (changedCoords.SequenceEqual(new int[] { pair1, pair2 }))
{
changedCoords.RemoveAt(i);
break;
}
}
}
// If any parsed coordinate exists beyond the bounds of the game grid, reject string
if (pair1 < 0 || pair1 > map.GetLength(0) || pair2 < 0 || pair2 > map.GetLength(1))
{
coordStringValid = false;
Console.WriteLine($"\nINVALID INPUT: Coordinate {pair} is out of bounds. Press any key to continue.");
// Press any key to continue
Console.ReadKey(true);
if (Console.KeyAvailable) { }
;
coordStringValid = false;
}
if (!coordStringValid) break;
coords.Add(new int[] { pair1, pair2 });
}
} while (!coordStringValid);
return coords;
}
else
{
return "ERROR: Code path error, user choice is neither by are type nor by coordinate selection";
}
}
// PRINT MAP BY TYPE (map, "complete/targets/changed", optional coords)
static void printMap(Location[,] map, string mapType, dynamic coords = null)
{
if (coords == null)
coords = new List() { };
string[][] icons = new string[][]
{
new string[] { "Wasteland", " w " },
new string[] { "Bombed Building", " b " },
new string[] { "Scrapyard", " s " },
new string[] { "Ruined Hospital", " r " },
new string[] { "Resistance Base", " # " },
new string[] { "HK-VTOL/HK-TANK/Harvester", " ▼ " },
};
Console.WriteLine(" 0 1 2 3 4 5 6 7 8 9");
// Function to replace lambda function call on lines 473 and 486. "Cannot use lamda function in dynamically called operation"
var checkSequence = (int[] coordItem, int i, int j) => {
return coordItem.Length == 2 && coordItem[0] == i && coordItem[1] == j;
};
// Iterate map, print location icons per requested map type
for (int i = 0; i < map.GetLength(0) ; i++){
Console.Write(i + " ");
for (int j = 0; j < map.GetLength(1); j++)
{
switch (mapType)
{
case "COMPLETE":
foreach (string[] item in icons)
{
if (map[i, j].type == item[0]){
Console.Write(item[1]);
break;
}
}
break;
default: // "TARGETS" or "CHANGED" type
// If no target coordinates are provided, or if coords data type is not List, reject and return
if (coords.GetType().GetGenericTypeDefinition() != typeof(List))
{
Console.Clear();
Console.WriteLine($"ERROR: No target coordinates provided. 'coords' arg type is {coords.GetType().GetGenericTypeDefinition()}\n");
Console.Write("PRESS ANY KEY TO CONTINUE: ");
Console.ReadKey(true);
if (Console.KeyAvailable) { };
return;
}
else
{
bool coordExists = false;
foreach (int[] coordItem in coords)
{
if (coordItem.Length == 2 && coordItem[0] == i && coordItem[1] == j)
{
coordExists = true;
break;
}
}
//if (Array.Exists(coords, checkSequence(coords[i,j], i, j))){
if (coordExists)
{
foreach (string[] areaType in icons)
{
if (map[i,j].type == areaType[0])
{
Console.Write(areaType[1]);
break;
}
}
}
else
{
Console.Clear();
Console.WriteLine($"COORD NOT FOUND: {coords[i, j]}\n");
foreach (int[] item in coords)
{
foreach (int num in item)
Console.Write($"{num}, ");
Console.WriteLine();
}
Console.WriteLine();
Console.Write("PRESS ANY KEY TO CONTINUE: ");
Console.ReadKey(true);
if (Console.KeyAvailable) { }
;
return;
}
}
break;
}
}
Console.WriteLine();
}
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/796 ... on-console