If 语句的更好语法
我有一个这样的条件:
if (string.IsNullOrEmpty(filename) || size != "Large" || size != "Medium" || size != "Small")
将来我可能必须在 if
语句中管理更多的 size
。
我想知道是否存在一种更易于管理和可读的方式来编写此条件。
请提供一个真实的例子,感谢您抽出宝贵的时间。
I have a condition like this one:
if (string.IsNullOrEmpty(filename) || size != "Large" || size != "Medium" || size != "Small")
Probability in future I will have to manage more size
in the if
statement.
I would like to know if exist a more manageable and readable way to write this condition.
Please provide a real example thanks for your time on this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您可以保留单词的哈希集并检查:
You can keep a hashset of words and check:
将尺寸放入某种集合中,并使用“包含”。有关示例,请参阅 MSDN: http://msdn.microsoft.com/en-us /library/bb352880.aspx
Put the sizes in a collection of some sort, and use "Contains". See MSDN for an example: http://msdn.microsoft.com/en-us/library/bb352880.aspx
如果它们要改变,也许静态列表更好:
对于更干净的代码,将大小检查封装到它自己的方法中,并在需要时修改该方法:
If they are going to change, perhaps a static list is better:
For even cleaner code, encapsulate the checking of size into it's own method and amend that method when required:
如果测试结果你要做不止一件事,将其写成 switch/case 可能会更具可读性。
否则,如果您有大量这些值,最好将列表保存在某个字典中 - 比如说
notHandledSizes
。分配“大”=>正确,“中”=> true,...只需检查该字典中的size
是否存在且为 true。If you have more than one thing to do as a result of the test, writing it out as a switch/case might be more readable.
Otherwise, if you have loads of those values, it might be nicer to keep the list in some dictionary - let's say
notHandledSizes
. Assign "Large" => true, "Medium" => true, ... and just check ifsize
is existing and true in that dictionary.选项 1:
编写一个返回 bool 值且仅包含大小测试的小函数,并在
if
中使用该函数。选项 2:
创建要测试的尺寸列表并使用
Contains
:您可以组合这两个选项以获得更好的清晰度和封装性。
Option 1:
Write a small function that returns a bool and that only contains the size tests and use that in your
if
.Option 2:
Create a list of sizes to test against and use
Contains
:And you can combine both options for better clarity and encapsulation.
下面的换行符使其更具可读性。
设计提示
如果许多对象涉及长 if 条件,那么最好在这些类中编写返回 true/false 的小属性/方法。
有时枚举标志属性也有助于这种情况。请参阅此处以获得详细解释。
Below line breaks makes it more readable.
Design Tip
If many objects involve with your long if condition, it's good to write small properties/methods that return true/false in those Classes.
Sometimes Enum Flags Attribute also helps such case. Look at here for a good explanation.
您所做的看起来是最直接的方法。任何修改都只会把混乱转移到其他地方。如果您不需要在其他地方重用此代码,我会保持原样。
What you have done looks the most direct way of doing it. Any modification will simply be moving the mess elsewhere. If you do not need to reuse this code anywhere else, I would leave it the way it is.