字符串和数字条件的最佳实践
我只是想知道如何编写必须表示为字符串的数字。
例如:
if (SelectedItem.Value == 0.ToString()) ...
或
if (SelectedItem.Value == "0") ...
或
public const string ZeroNumber = "0";
if (SelectedItem.Value == _zeroNumber) ...
或
if (Int.Parse(SelectedItem.Value) == 0)
I just wonder how to write a number that has to be expressed as string.
For instance:
if (SelectedItem.Value == 0.ToString()) ...
or
if (SelectedItem.Value == "0") ...
or
public const string ZeroNumber = "0";
if (SelectedItem.Value == _zeroNumber) ...
or
if (Int.Parse(SelectedItem.Value) == 0)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于单个测试,我个人会选择
它,没有大惊小怪,没有仪式 - 它准确地说明了您想要做的事情。
另一方面,如果我有一个应该是数字的值,然后我将根据该数字做出反应,我会使用:
For a single test, I'd personally go with
It has no fuss, no ceremony - it says exactly what you're trying to do.
On the other hand, if I have a value which should be a number, and then I'll react based on that number, I'd use:
如果该值是一个整数,并且这就是它自然应该使用的用途,那么我会将其解析为 int - 即使用最适合数据含义的类型。
例如,无论如何,下拉列表通常都是从数据库查找表中填充的 - 如果它将项目键存储为整数,那么我认为您应该始终将其作为一个来处理。同样,如果所选项目的键再次存储在数据库中,那么无论如何它都需要在某个时候转换为 int 。
If the value is meant to be an integer, and that is what it should be naturally used for then I'd parse it to an int - i.e. use the type that's most appropriate for the meaning of the data.
For example, often dropdown lists are populated from a database lookup table anyway - if that stores the item key as an integer then I think you should consistently handle it as one. Likewise, if the key of selected item is being stored in the db again then it needs to be converted to an int at some point anyway.
使用尝试解析。
Use TryParse.