цикл c # в публичном статическом классе - PullRequest
0 голосов
/ 11 января 2019

Я новичок в C # и пытаюсь сделать цикл в классе, но не знаю, как это сделать; v

нужно сделать что-то подобное:

namespace MyApp
{
    using [...]


    public static class MyClass
    {
        private const string Options = [...];


        [Option("option#")]
        public static void Option#([...])
        {
            [...]
        }



        # is value from for loop {i} and below is inside loop 
        e.g.

        for (int i = 0; i < 5; i++)
        {

            [Option("option{i from loop}")]
            public static void Option{i from loop}([...])
            {
                My code
            }

        }

Как мне этого добиться? Мне нужно добавить команду / public в цикле к классу MyClass. Цикл создания команды и public для команды и добавление в класс при запуске скомпилированного файла .exe, а не при создании .exe Любая помощь приветствуется, надо учиться;)

Ответы [ 2 ]

0 голосов
/ 11 января 2019

Вот пример класса 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();
    }
}

выход

![enter image description here

0 голосов
/ 11 января 2019
public static void MyAwesomeChangingMethod(int i)
{
    Console.WriteLine(i);
}

...

// now you can call it many times with a different number
MyAwesomeChangingMethod(1);
MyAwesomeChangingMethod(3);
MyAwesomeChangingMethod(675675);

// or

for (int i = 0; i < 5; i++)
    MyAwesomeChangingMethod(i);

Примечание : Если это не то, что вы хотите, вам действительно нужно лучше объяснить свой вопрос (не в комментариях)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...