公共静态类中的C#循环

时间:2019-01-11 00:30:46

标签: c# loops class static

我是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
            }

        }

我该如何实现?我需要在循环中向类MyClass添加命令/公共。循环生成命令并为命令生成公共代码,并在运行编译的.exe文件时(而不是在生成.exe时)添加到类中 欢迎大家的帮助,必须学习;)

2 个答案:

答案 0 :(得分:2)

这是一个static类的示例,该类通过称为AddCommands的方法(使用for循环)将字符串(以及数字)添加到私有列表中。它使用foreach循环来显示ShowCommands方法中的命令:

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

答案 1 :(得分:0)

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);

注意 :如果这不是您想要的,那么您确实需要更好地解释您的问题(不在注释中)