【问题标题】:Switch Statement with Strings C#带有字符串 C# 的 Switch 语句
【发布时间】:2009-11-14 20:09:06
【问题描述】:

我需要写一些东西来获取启动参数,然后为这些启动参数做一些事情,我认为 switch 会很好,但它只接受整数,它必须是字符串

这不是实际的代码,但我想知道如何使这样的东西工作

namespace Simtho
{
    class Program
    {
        static void Main(string[] args)
        {
            switch (Environment.GetCommandLineArgs())
            {

                case "-i":
                    Console.WriteLine("Command Executed Successfully");
                    Console.Read;
                    break;
            }
        }

    }
}

【问题讨论】:

  • 你可以打开字符串就好了。

标签: c# string switch-statement


【解决方案1】:

Environment.GetCommandLineArgs() 返回一个字符串数组。无法打开阵列。尝试遍历数组的成员,如下所示:

namespace Simtho
{
    class Program
    {
        static void Main(string[] args)
        {
            foreach (string arg in Environment.GetCommandLineArgs())
            {
                switch (arg)
                {

                    case "-i":
                        Console.WriteLine("Command Executed Successfully");
                        Console.Read();
                        break;
                }
            }
        }
    }
}

【讨论】:

    【解决方案2】:

    这样的事情呢?

    string[] args = Environment.GetCommandLineArgs();
    
    if (args.Contains("-i"))
    {
        // Do something
    }
    

    【讨论】:

      【解决方案3】:

      Environment.GetCommandLineArgs() 返回字符串数组?

      也许我错了,但在内部将字符串转换为 if-else 序列...

      【讨论】:

        【解决方案4】:

        Environment.GetCommandLineArgs() 返回一个string[]

        您不能打开字符串数组。不过,您可能想测试数组是否包含某些值。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-08-26
          • 2012-10-24
          • 1970-01-01
          • 1970-01-01
          • 2020-12-06
          • 2016-12-12
          • 2023-03-15
          相关资源
          最近更新 更多