切换声明是我喜爱switch与if/else if构造的个人主要原因之一.这里有一个例子:
static string NumberToWords(int number)
{
string[] numbers = new string[]
{ "", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine" };
string[] tens = new string[]
{ "", "", "twenty", "thirty", "forty", "fifty",
"sixty", "seventy", "eighty", "ninety" };
string[] teens = new string[]
{ "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen" };
string ans = "";
switch (number.ToString().Length)
{
case 3:
ans += string.Format("{0} hundred and ", numbers[number / 100]); …Run Code Online (Sandbox Code Playgroud) 假设有以下代码:
private static int DoSwitch(string arg)
{
switch (arg)
{
case "a": return 0;
case "b": return 1;
case "c": return 2;
case "d": return 3;
}
return -1;
}
private static Dictionary<string, Func<int>> dict = new Dictionary<string, Func<int>>
{
{"a", () => 0 },
{"b", () => 1 },
{"c", () => 2 },
{"d", () => 3 },
};
private static int DoDictionary(string arg)
{
return dict[arg]();
}
Run Code Online (Sandbox Code Playgroud)
通过迭代这两种方法并进行比较,即使"a","b","c","d"扩展为包含更多键,我也会得到字典稍快一些.为什么会这样?
这与圈复杂度有关吗?是因为抖动只将字典中的return语句编译为本机代码一次?是因为字典的查找是O(1),这可能不是switch语句的情况?(这些只是猜测)
我想重构以下代码以避免if ... else以便每次进入新的调查类型时都不必更改方法(开放/封闭原则).以下是我正在考虑重构的一段代码:
if (surveyType == SurveySubType.Anonymous)
{
DoSomething(param1, param2, param3);
}
else if (surveyType == SurveySubType.Invitational)
{
DoSomething(param1);
}
else if (surveyType == SurveySubType.ReturnLater)
{
DoSomething(param1);
}
Run Code Online (Sandbox Code Playgroud)
为了解决这个问题,我添加了以下类:
public abstract class BaseSurvey
{
public string BuildSurveyTitle()
{
...doing something here
}
public abstract void DoSomething(int? param1,int? param2,int? param3);
}
public class InvitationalSurvey: BaseSurvey
{
public override void DoSomething(int? param1,int? param2,int? param3)
{
//I don't need param2 and param3 here
}
}
public class ReturnLaterSurvey: BaseSurvey
{
public override void …Run Code Online (Sandbox Code Playgroud) 我记得过去enum在语句中使用 s switch,并且根据C# how to use enum with switch我正在以正确的方式这样做。但我刚刚尝试再次执行此操作,但收到以下错误:
“ApplicationMode”是一种“类型”,但使用方式类似于“变量”。
这是我正在使用的代码:
public static enum ApplicationMode
{
Edit,
Upload,
Sync,
None
}
private void edit_Click(object sender, EventArgs e)
{
switch(ApplicationMode) // This is where I see the error.
{
case ApplicationMode.Edit:
break;
...
}
}
Run Code Online (Sandbox Code Playgroud)
我做错了什么?