2011-11-17 105 views
2

我总共有102个值与名为ArrivedFlag的字段名相关联。是否有更有效的方法来管理IF语句?

然后我在标记页上有一个TextBox控件,其ID为txtFlag

在我隐藏,我有一个if语句,说:

If txtFlag <> "value1" and txtFlag <> "another value" Then 
    lblMessage.Text ="You don't have the ability to view details" 
end if 

这工作得很好。

但是,考虑到有102个值,我觉得做102次IF语句有点低效。

有没有人知道更好的方法来处理这个问题?

Dim allowedFlags = New List(Of String)() 

With { _ 
    "value1", _ 
    "another value" 
} 
End With 
If Not allowedFlags.Contains(txtFlag) Then 
    lblMessage.Text = "You don't have the ability to view details" 
End If 

回答

2

值添加到列表中,然后使用。载

// hopefully you can get the 102 strings from an xml document or db 
var listOfFlags = new List<string> { "value1", "another value", .... }; 

if (!listOfFlags.Contains(txtFlag)) 
{ 
    lblMessage.Text = "you dont' have ..." 
} 
+0

经过一些微小的修改后,这对我来说效果很好。谢谢你,感谢所有贡献者。 – Kenny

2

“switch”语句会更干净,虽然102个“case”仍然有点混乱。 如果你采用了战略模式,你可能会遇到一些“阶级爆炸”的措施。

我可能从一个switch语句开始,然后看看提取一些常见的行为和朝着战略模式的方向。

2

把你的允许值到一个数组,然后只查询用户的选择是否是数组中:

if(!allowedFlags.Contains(txtFlag)) 
    lblMessage.Text ="You don't have the ability to view details"; 

更好的是,您可以使用HashSet<string>作为允许的值,以便您有O(1)查找时间。

+0

非常感谢您的时间和帮助。我喜欢Jason's和BrokenGlass的解决方案,但是我很难让它工作。即使从我创建的列表中进行选择,我仍然会收到“您无法查看详细信息”。我已经更新了上面的当前代码。 – Kenny

相关问题