字符串和数字条件的最佳实践

发布于 2024-08-21 01:59:36 字数 375 浏览 2 评论 0原文

我只是想知道如何编写必须表示为字符串的数字。

例如:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

玻璃人 2024-08-28 01:59:36

对于单个测试,我个人会选择

if (SelectedItem.Value == "0")

它,没有大惊小怪,没有仪式 - 它准确地说明了您想要做的事情。

另一方面,如果我有一个应该是数字的值,然后我将根据该数字做出反应,我会使用:

int value;
// Possibly use the invariant culture here; it depends on the situation
if (!int.TryParse(SelectedItem.Value, out value))
{
    // Throw exception or whatever
}
// Now do everything with the number directly instead of the string

For a single test, I'd personally go with

if (SelectedItem.Value == "0")

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 value;
// Possibly use the invariant culture here; it depends on the situation
if (!int.TryParse(SelectedItem.Value, out value))
{
    // Throw exception or whatever
}
// Now do everything with the number directly instead of the string
冷…雨湿花 2024-08-28 01:59:36

如果该值是一个整数,并且这就是它自然应该使用的用途,那么我会将其解析为 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.

溺渁∝ 2024-08-28 01:59:36

使用尝试解析

string value = "123";
int number;
bool result = Int32.TryParse(value, out number);
if (result)
{
    ...

Use TryParse.

string value = "123";
int number;
bool result = Int32.TryParse(value, out number);
if (result)
{
    ...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文