繁体   English   中英

公共静态类中的C#循环

[英]c# loop in public static class

我是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时添加到类中。欢迎大家的帮助,必须学习;)

这是一个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();
    }
}

输出量

![在此处输入图片描述

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM