如何使用字符串数组来处理C#中switch语句中的case?

Dam*_*ien 2 c# arrays

我有一个阵列

    public static string[] commands =
    {   
        "command1",
        "command2",
        "command3",
        "command4",
        "command5",
        "command6",
        "command7"
    };
Run Code Online (Sandbox Code Playgroud)

我想在函数中使用数组

    public static bool startCommand (string commandName) {
        //stuff
        if (commandName == commands[0]) {
            //stuff
            return true;
        }
        else {
            //stuff
            switch (commandName) {
                case commands [1]:
                    //stuff
                    break;
                case commands [2]:
                    //stuff
                    break;
                case commands [3]:
                    //stuff
                    break;
                case commands [4]:
                    //stuff
                    break;
                case commands [5]:
                    //stuff
                    break;
                case commands [6]:
                    //stuff
                    break;
                default:
                    return false;
            }
            //do stuff
            return true;
        }
    }
Run Code Online (Sandbox Code Playgroud)

这给我的错误是每个案例的"一个恒定值".

我可以使用if和else语句,但我认为switch语句看起来更好.

除非我错过了我的标记,否则我的数组是常量字符串,所以这应该有效.任何帮助,将不胜感激.很抱歉,如果这是一个新问题,我已经用C#编程了大约四天.

Ayd*_*din 7

您正在寻找的是Dictionary<TKey, TValue>类型.A Dictionary基本上是Key-Value对的集合,我们可以利用它来实现您想要实现的目标.

使用您给出的示例,实现将如下所示:

Dictionary<string, Action> commandsDictionary = new Dictionary<string, Action>();
commandsDictionary.Add("Command1", () => Console.WriteLine("Command 1 invoked"));
commandsDictionary.Add("Command2", () => Console.WriteLine("Command 2 invoked"));

commandsDictionary["Command2"].Invoke();
// Command 2 invoked
Run Code Online (Sandbox Code Playgroud)

正如您已经注意到的那样,我已经介绍了一个没有任何参数的Action委托.


要引入参数,只需将其指定为类型参数,如下所示: Action<int>

Dictionary<string, Action<int>> commandsDictionary = new Dictionary<string, Action<int>>();
commandsDictionary.Add("Command1", (i) => Console.WriteLine("Command {0} invoked", i));

commandsDictionary["Command1"].Invoke(1);
// Command 1 invoked
Run Code Online (Sandbox Code Playgroud)

如果要从正在调用的委托中返回一个值,请使用Func委托,一个易于记忆的规则Func是,最后一个类型参数始终是返回的类型,因此Func<int, string>等同于具有以下签名的方法public string Foo(int i)

Dictionary<string, Func<int, string>> commandsDictionary = new Dictionary<string, Func<int, string>>();
commandsDictionary.Add("Command1", (i) => { return string.Format("Let's get funky {0}", i); });

string result = commandsDictionary["Command1"].Invoke(56963);
Console.WriteLine (result);
// Let's get funky 56963
Run Code Online (Sandbox Code Playgroud)


参考

我已经添加了这一部分来帮助那些还不知道代表是什么的人...这一切都非常简单.


代表

一个DelegateType代表引用的方法.它们就像你声明引用对象的变量一样,除了代替对象,它们引用方法.

委托可以使用命名方法匿名函数(例如lambda表达式(我在上面演示的类型))进行实例化.


行动代表

Action Delegate具有的返回类型无效,并与类型参数定义了它的签名.

void Example()
{
    // Named method
    this.NamedActionDelegate = NamedMethod;
    this.NamedActionDelegate.Invoke("Hi", 5);
    // Output > Named said: Hi 5

    // Anonymous Function > Lambda
    this.AnonymousActionDelegate.Invoke("Foooo", 106);
    // Output > Anonymous said: Foooo 106
}

public Action<string, int> NamedActionDelegate { get; set; }
public Action<string, int> AnonymousActionDelegate = (text, digit) => Console.WriteLine ("Anonymous said: {0} {1}", text, digit);

public void NamedMethod(string text, int digit)
{
    Console.WriteLine ("Named said: {0} {1}", text, digit);
}
Run Code Online (Sandbox Code Playgroud)

Func代表

Func Delegate类似于动作代表不同的是函数功能永远不会返回无效,因此总是需要至少1类型参数和前面所提到的,最后指定的类型参数决定了委托的返回类型.

void Example()
{
    // Named method
    this.NamedFuncDelegate = NamedMethod;
    string namedResult = this.NamedFuncDelegate.Invoke(5);
    Console.WriteLine (namedResult);
    // Output > Named said: 5

    // Anonymous Function > Lambda
    string anonyResult = this.AnonymousFuncDelegate.Invoke(106);
    Console.WriteLine (anonyResult);
    // Output > Anonymous said: 106
}

public Func<int, string> NamedFuncDelegate { get; set; }
public Func<int, string> AnonymousFuncDelegate = (digit) => { return string.Format("Anonymous said: {0}", digit); };

public string NamedMethod(int digit)
{
    return string.Format ("Named said: {0}", digit);
}
Run Code Online (Sandbox Code Playgroud)