C#中有没有像SQL中的isnull一样的函数?

时间:2015-01-04 05:40:25

标签: c# sql sql-server function

在SQL服务器中,我们可以使用“isnull”函数,例如,如果Table1包含Field1,并且只有一条Field1为null的记录,我们可以编写此查询:

select isnull(Field1,0) from Table1

返回“0”。

我们可以在C#中使用这样的任何函数吗?例如,考虑textBox1为空。我想显示“0”。

MessageBox.show( FunctionName(textBox1.text , 0).toString());

6 个答案:

答案 0 :(得分:5)

您可以创建扩展方法:

internal static class MyStringExtensions {

   public static string GetValueOrDefault(this string extendee, string defaultValue) {

     if(string.IsNullOrEmpty(extendee)) { return defaultValue;}
     return extendee;
   }
}

样品使用:

MessageBox.show( textBox1.text.GetValueOrDefault("0"));

答案 1 :(得分:1)

您可以通过这种方式轻松完成,这与使用函数一样好:

MessageBox.show(String.IsNullOrEmpty(textBox1.Text) ? "" : textBox1.text);

答案 2 :(得分:1)

尝试

MessageBox.show(String.IsNullOrEmpty(textBox1.Text) ? "0" : textBox1.text);

答案 3 :(得分:0)

您可以创建自己的功能:

int myfun(String text) {
    if (string.IsNullOrEmpty(text)) {
        return 0;
    }
    return 1;
}

答案 4 :(得分:0)

使用IsNullOrEmpty

if (String.IsNullOrEmpty(textBox1.Text)) 

答案 5 :(得分:0)

您可以像这样使用null-coalescing operator

MessageBox.show( textBox1.text ?? "0" );

请注意,在??的右侧,值必须与左侧的类型相同,或者是隐式转换为右侧类型的类型。在示例中,两个值都是string类型,所以一切都很好。

另请注意,如果值为空而不是null,则返回空字符串。

相关问题