【问题标题】:BestPractice for conditions with strings and numbers字符串和数字条件的最佳实践
【发布时间】:2011-01-15 04:33:03
【问题描述】:

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

例如:

if (SelectedItem.Value == 0.ToString()) ...

if (SelectedItem.Value == "0") ...

public const string ZeroNumber = "0";
if (SelectedItem.Value == _zeroNumber) ...

if (Int.Parse(SelectedItem.Value) == 0)

【问题讨论】:

  • @Asad Butt - 为什么这很重要?

标签: c# string integer


【解决方案1】:

对于单个测试,我会亲自去

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

【讨论】:

    【解决方案2】:

    如果该值是一个整数,并且它应该自然地用于它,那么我会将它解析为一个 int - 即使用最适合数据含义的类型。

    例如,下拉列表通常是从数据库查找表中填充的 - 如果将项目键存储为整数,那么我认为您应该始终将其作为一个来处理。同样,如果所选项目的键再次存储在数据库中,则无论如何都需要将其转换为 int。

    【讨论】:

      【解决方案3】:

      使用TryParse

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-10
        • 1970-01-01
        • 2018-12-18
        • 1970-01-01
        相关资源
        最近更新 更多