问题描述
我有以下代码,我目前正在使用......基本上,这个方法为每个任务分配正确的布尔标志(真/假).随着需要添加的任务越来越多......我可以看到 switch 语句将不得不增加以适应每项任务.
I have the following code which I am are currently using .... Basically, this method assigns the correct boolean flag (TRUE/FALSE) for each Task. As more and more tasks need to be added .. I can see that the switch statement will have to grow to cater for every task.
必须有一种更简单的方法......保持方法小.
There has to be an easier way ... to keep the method small.
代码:(忘记命名约定,发帖已改)
Code: (forget naming convention, it has been changed for posting)
public ClassStructure.User AssignTaskStatusToUser(ClassStructure.User,
List<ClassStructure.Tasks> TaskStatus)
{
foreach (ClassStructure.Tasks data in TaskStatus)
{
string Task_CallID = data.Task_Call_ID;
switch (Task_CallID)
{
case ClassStructure.Tasks_CallIDs_Strings.TASK1:
User.TASK1 = data.Task_Flag;
break;
case ClassStructure.Tasks_CallIDs_Strings.TASK2:
User.TASK2 = data.Task_Flag;
break;
case ClassStructure.Tasks_CallIDs_Strings.TASK3:
User.TASK3 = data.Task_Flag;
break;
}
}
return User;
}
ClassStructure.Tasks_CallIDs_Strings = 任务的字符串表示
ClassStructure.Tasks_CallIDs_Strings = String Representation of the Tasks
data.Task_Flag = 布尔值
data.Task_Flag = boolean
User.TASKX = 布尔值
User.TASKX = boolean
欢迎任何反馈.我相信有一个简单的解决方案.
Any feedback is welcome. I am sure there is an easy solution.
推荐答案
对于很多这样的值,我会使用这样的映射:
For a lot of values like these, I would use a map something like this:
Dictionary<ClassStructure.Tasks_CallIDs_Strings, Task_Flag>
并通过映射 CallIDs 字符串检索值.
and retrieve values by mapping the CallIDs strings.
正如大家现在看到的,重构这个例子的真正问题在于重构 User.TASKX.让它成为一个列表就足够了 - 因为它可以被相同的字符串索引 ClassStructure.Tasks_CallIDs_Strings
As everyone can now see, the real problem of refactoring this example lies in refactoring User.TASKX. Making it a list should suffice - as it could then be indexed by the same string ClassStructure.Tasks_CallIDs_Strings
这篇关于重构我的 C# 代码 - Switch 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!