Вот пример класса static
, который добавляет строки (вместе с числом) в закрытый список с помощью метода с именем AddCommands
, который использует цикл for
. Для отображения команд в методе ShowCommands
используется цикл foreach
:
static class Commander
{
private static List<string> Commands;
public static void AddCommands(string command, int count)
{
if (Commands == null) Commands = new List<string>();
int startValue = Commands.Count + 1;
int endValue = startValue + count;
for (int i = startValue; i < endValue; i++)
{
Commands.Add(command + i);
}
}
public static void ShowCommands()
{
if ((Commands?.Any()).GetValueOrDefault())
{
foreach (var command in Commands)
{
Console.WriteLine(command);
}
}
else
{
Console.WriteLine("There are no commands available.");
}
Console.WriteLine("-------------------\n");
}
}
И вот пример его использования:
class Program
{
private static void Main()
{
Console.WriteLine("Before adding any commands the list looks like:");
Commander.ShowCommands();
Commander.AddCommands("SomeCommand", 5);
Console.WriteLine("After adding 5 commands the list looks like:");
Commander.ShowCommands();
Commander.AddCommands("AnotherCommand", 5);
Console.WriteLine("After adding 5 more commands the list looks like:");
Commander.ShowCommands();
Console.WriteLine("Done! Press any key to exit...");
Console.ReadKey();
}
}
выход