c#空字符串 - >空值?

时间:2012-04-24 09:15:59

标签: c# .net-4.0

我有很多次输入文字,

如果它为空(用户没有输入任何文本) - 我想发送到数据库查询“null”

String.Empty.(或“”)

所以我发现自己做了很多这样的事情:

var mySqlValue =  string.IsNullOrEmpty( tbCustomerId.Text)?null:tbCustomerId.Text;

这对我来说似乎很难看。

.net为相反的场景提供了许多其他解决方案:

        string.IsNullOrEmpty
        string.IsNullOrWhiteSpace
        myProblemVal ?? myDefultVal

我知道这可以通过扩展方法解决 - 我知道如何做到这一点..

但有什么更好的吗?

是否有任何智能代码:“if its empty -> null”。

4 个答案:

答案 0 :(得分:19)

您可以使用扩展方法:

public static class Extensions {
    public static string NullIfWhiteSpace(this string value) {
        if (String.IsNullOrWhiteSpace(value)) { return null; }
        return value;
    }
}

你可以这样使用:

var mySqlValue = tbCustomerId.Text.NullIfWhiteSpace();

我真的不知道你想象的东西比扩展方法更好。你如何定义“更好”?短?使用特殊关键字?使用很少使用的运算符看起来很聪明?这已经只是附加到您的值的单个方法调用,它甚至可以在空值上工作,并且您所需的逻辑无法以比此更短的方式表达。另外,我不知道它的任何特殊语法。

答案 1 :(得分:7)

  

但有什么更好的吗?

不,虽然我认为你在问题中描述的内容(扩展方法)绝对没问题。正如您在问题中所描述的那样,在另一个方向上,您具有无效合并。

答案 2 :(得分:5)

声明自己的静态方法:

public static string NullIfEmpty(string value)
{
  return string.IsNullOrEmpty(value) ? null : value;
}

否则

MyHelper.NullIfEmpty(value)并不比调用字符串类型的静态方法更糟糕...而且它似乎比每次写入“string.IsNullOrEmpty(tbCustomerId.Text)?null:tbCustomerId.Text”更清晰。

答案 3 :(得分:0)

从您的字符串开始

                        <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent">

                        <android.support.design.widget.TextInputLayout
                            style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:layout_marginEnd="10dp">

                            <android.support.design.widget.TextInputEditText
                                android:id="@+id/myprofile_twitter"
                                android:layout_width="match_parent"
                                android:textColor="@color/blue_grey_800"
                                android:layout_height="wrap_content"
                                android:hint="Twitter" />

                        </android.support.design.widget.TextInputLayout>

                        <Switch
                            android:id="@+id/twitter_switch"
                            android:layout_width="45dp"
                            android:layout_height="30dp"
                            android:layout_marginEnd="10dp"
                            android:layout_gravity="center_vertical"/>

                    </LinearLayout>

编写一种将空白转换为null的方法

string myString = "";

然后包装该方法,并使用您在SQL中期望的相同语法对其进行调用

public static string NullIf(string value)
{
    if (String.IsNullOrWhiteSpace(value)) { return null; }
    return value;
}