use*_*322 9 c# dictionary switch-statement
在我的代码中,我想处理在数据包中编码为一个符号的项目的文本名称.
在通常的情况下,对我1012来说意味着cat, dog, cat, frog,但是还有更多像这样的对,所以很难记住所有这些.有时他们需要改变,所以我认为我应该Dictionary<string, int>为此目的使用.但是之后…
switch (symbol)
{
case "0": { /* ... */ }
case "1": { /* ... */ }
case "2": { /* ... */ }
case "n": { /* ... */ }
}
Run Code Online (Sandbox Code Playgroud)
... ...变
switch (symbol)
{
case kvpDic["cat"]: { /* ... */ }
case kvpDic["dog"]: { /* ... */ }
case kvpDic["frog"]: { /* ... */ }
case kvpDic["something else"]: { /* ... */ }
}
Run Code Online (Sandbox Code Playgroud)
而工作室说我需要为我的开关使用常量.
我如何使其工作?
更新:此类动物的数量及其值对仅在运行时已知,因此代码不得使用常量(我猜).
sco*_*ttm 18
您可以存储Func<T>或Action在字典中存储.
var dict = new Dictionary<int, Action>();
dict.Add(1, () => doCatThing());
dict.Add(0, () => doDogThing());
dict.Add(2, () => doFrogThing());
Run Code Online (Sandbox Code Playgroud)
然后,像这样使用它:
var action = dict[1];
action();
Run Code Online (Sandbox Code Playgroud)