【问题标题】:Convert Empty to Null将空转换为空
【发布时间】:2014-02-20 16:10:48
【问题描述】:
Convert.ToString(icdoCalcWiz.ihstOldValues[enmCalcWiz.position_value.ToString()])!=icdoCalcWiz.position_value

这里 LHS 的值将是 ""(Empty)

但在 RHS 中该值为 NULL

我必须满足 Empty 或 Null 都相等的条件

但根据上述条件,两者都不是:

【问题讨论】:

    标签: c#


    【解决方案1】:

    使用这个。

    if (string.IsNullOrEmpty("any string"))
    {
    }
    

    还有一个方法 String.IsNullOrWhitespace() 指示指定的字符串是 null、空还是仅由空白字符组成。

    if(String.IsNullOrWhitespace(val))
    {
        return true;
    }
    

    上面是下面代码的快捷方式:

    if(String.IsNullOrEmpty(val) || val.Trim().Length == 0)
    {
        return true;
    }
    

    【讨论】:

      【解决方案2】:

      你可以试试这个....

      static string NullToString( object Value )
      {
      
          // Value.ToString() allows for Value being DBNull, but will also convert int, double, etc.
          return Value == null ? "" : Value.ToString();
      
          // If this is not what you want then this form may suit you better, handles 'Null' and DBNull otherwise tries a straight cast
          // which will throw if Value isn't actually a string object.
          //return Value == null || Value == DBNull.Value ? "" : (string)Value;
      }
      

      您的代码将写为....

      Convert.ToString(icdoCalcWiz.ihstOldValues[enmCalcWiz.position_value.ToString()])!=
      NullToString(icdoCalcWiz.position_value)
      

      【讨论】:

        【解决方案3】:

        我认为以下线程可能会帮助您解决此问题

        String Compare where null and empty are equal

        否则你可以检查null并分配空字符串并进行比较

        【讨论】:

          【解决方案4】:

          怎么样

          string lhs = Convert.ToString(icdoCalcWiz.ihstOldValues[enmCalcWiz.position_value.ToString()]);
          string rhs = icdoCalcWiz.position_value;
          
          if ( (lhs == null || lhs == string.Empty) && (rhs == null || rhs == string.Empty)){
            return true;
          } else {
            return lhs == rhs;
          }
          

          【讨论】:

            猜你喜欢
            • 2012-05-04
            • 2020-03-22
            • 1970-01-01
            • 2017-06-14
            • 2012-02-18
            • 1970-01-01
            • 1970-01-01
            • 2012-12-11
            • 2018-06-12
            相关资源
            最近更新 更多