可空值可以同时考虑null("")和DBNull

时间:2015-05-13 10:03:00

标签: c# asp.net double nullable dbnull

如果数据库中的a列有""或DBNull它应该取为0。

我能把它放在一行吗?无论如何,我做了很长时间的编码。有没有更短的方法来实现这一目标。

这是我的代码:

public string difference(object val1, object val2)
    {

        double value1 = 0;
        double value2 = 0;
        if (val1 == "" && val2 == "")
        {            
            value3 = value1 - value2;
        }
        else if (val1 != "" && val2 != "")
        {
            if (val1 != DBNull.Value && val2 != DBNull.Value)
            {
                value1 = Convert.ToDouble(val1);
                value2 = Convert.ToDouble(val2);
                value3 = value1 - value2;
            }
            else if (val1 == DBNull.Value && val2 == DBNull.Value)
            {

                value3 = value1 - value2;
            }
            else if (val1 != DBNull.Value && val2 == DBNull.Value)
            {
                value1 = Convert.ToDouble(val1);

                value3 = value1 - value2;
            }
            else
            {                
                value2 = Convert.ToDouble(val2);
                value3 = value1 - value2;
            }

        }
        else if (val1 == "" && val2 != "")
        {
            if (val2 == DBNull.Value)
            {
                value3 = value1 - value2;
            }
            else
            {
                value2 = Convert.ToDouble(val2);
                value3 = value1 - value2;
            }
        }
        else
        {
            if (val1 == DBNull.Value)
            {
                value3 = value1 - value2;
            }
            else
            {
                value1 = Convert.ToDouble(val1);
                value3 = value1 - value2;
            }
        }
            return Convert.ToString(value3);        
    }

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

您的方法可以简单地写成

Spring boot

假设public double Difference(object val1, object val2) { double value1; double value2; double.TryParse(val1.ToString(), out value1); double.TryParse(val2.ToString(), out value2); return value1 - value2; } val1永远不为空(对于您的代码也是如此)。我还将返回类型设为val2。如果你想要它作为字符串调用double方法。