Kyl*_*ndo 15 .net c# switch-statement
我目前的switch声明大约有300多行.我知道这不是它可以获得的巨大,但我确信有更好的方法来处理这个问题.
switch语句Enum用于确定与日志记录相关的某些属性.现在问题在于,很容易省略枚举值,并且不会给它一个值,因为它不在switch语句中.
是否有一个选项可以用来确保每个枚举都被使用并给定一组自定义值来完成它的工作?
编辑:
请求的代码示例:(这很简单,但显示我的意思.此外,还会存在具有以下值的枚举.)
internal void GenerateStatusLog(LogAction ActionToLog)
{
switch (ActionToLog)
{
case LogAction.None:
{
return;
}
case LogAction.LogThis:
{
ActionText = "Logging this Information";
LogText = "Go for it.";
break;
}
}
// .. Do everything else
}
Run Code Online (Sandbox Code Playgroud)
编辑
我再次想到这一点,在SO中查看相关问题,我写了一些代码.我创建了一个名为的类AdvancedSwitch<T>,它允许您添加案例并公开一个方法来评估一个值,并允许您指定它应检查存在的值.
这就是我想出的:
public class AdvancedSwitch<T> where T : struct
{
protected Dictionary<T, Action> handlers = new Dictionary<T, Action>();
public void AddHandler(T caseValue, Action action)
{
handlers.Add(caseValue, action);
}
public void RemoveHandler(T caseValue)
{
handlers.Remove(caseValue);
}
public void ExecuteHandler(T actualValue)
{
ExecuteHandler(actualValue, Enumerable.Empty<T>());
}
public void ExecuteHandler(T actualValue, IEnumerable<T> ensureExistence)
{
foreach (var val in ensureExistence)
if (!handlers.ContainsKey(val))
throw new InvalidOperationException("The case " + val.ToString() + " is not handled.");
handlers[actualValue]();
}
}
Run Code Online (Sandbox Code Playgroud)
你可以这样使用这个类:
public enum TrafficColor { Red, Yellow, Green }
public static void Main()
{
Console.WriteLine("Choose a traffic color: red, yellow, green?");
var color = (TrafficColor)Enum.Parse(typeof(TrafficColor), Console.ReadLine());
var result = string.Empty;
// Creating the "switch"
var mySwitch = new AdvancedSwitch<TrafficColor>();
// Adding a single case
mySwitch.AddHandler(TrafficColor.Green, delegate
{
result = "You may pass.";
});
// Adding multiple cases with the same action
Action redAndYellowDelegate = delegate
{
result = "You may not pass.";
};
mySwitch.AddHandler(TrafficColor.Red, redAndYellowDelegate);
mySwitch.AddHandler(TrafficColor.Yellow, redAndYellowDelegate);
// Evaluating it
mySwitch.ExecuteHandler(color, (TrafficColor[])Enum.GetValues(typeof(TrafficColor)));
Console.WriteLine(result);
}
Run Code Online (Sandbox Code Playgroud)
通过匿名代表的创造性使用,您可以轻松地将新案例添加到"切换块"中.:)
不是说你也可以使用lambda表达式和lambda块,例如() => { ... }代替delegate { ... }.
您可以轻松使用此类而不是长开关块.
原帖:
如果使用Visual Studio,请始终swich使用switch代码段创建语句.键入switch两次按Tab键,它会自动为您生成所有可能性.
然后,default在结尾处添加一个引发异常的案例,这样在测试你的应用程序时你会立即注意到有一个未处理的案例.
我的意思是这样的:
switch (something)
{
...
case YourEnum.SomeValue:
...
break;
default:
throw new InvalidOperationException("Default case reached.");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5447 次 |
| 最近记录: |