简体   繁体   English

是否有内置的 C# 方法将 go 从空字符串转换为 null 值?

[英]Is there a built-in C# method to go from an empty string to null value?

There are many times in which I have an input text, and, if it's empty (if the user didn't type any text, for example), I want to send a null value to the DB query.有很多次我有一个输入文本,如果它是空的(例如,如果用户没有输入任何文本),我想向数据库查询发送一个 null 值。

I do not want to send String.Empty.不想发送String.Empty. (or "" ). (或"" )。

Thus I find myself doing this a lot:因此我发现自己经常这样做:

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

This seems ugly to me.这对我来说似乎很难看。 .NET gives a lot of other solutions for the opposite scenarios: .NET针对相反的场景给出了很多其他的解决方案:

string.IsNullOrEmpty
string.IsNullOrWhiteSpace
myProblemVal ?? myDefultVal

Is there anything built-in to C# that lets me do this a shorter way, like the opposite direction? C# 是否有任何内置功能可以让我以更短的方式执行此操作,例如相反的方向?

I know this can be solved by writing my own extension methods and I know how to do that;我知道这可以通过编写自己的扩展方法来解决,而且我知道该怎么做; that's not a solution I'm interested in.那不是我感兴趣的解决方案。

I'm looking for some code like " if empty -> null ".我正在寻找一些代码,如“ if empty -> null ”。

You can use an extension method: 您可以使用扩展方法:

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

Which you could use like that: 你可以这样使用:

var mySqlValue = tbCustomerId.Text.NullIfWhiteSpace();

I don't really know what you imagine by something better than Extension methods. 我真的不知道你想象的东西比扩展方法更好。 How do you define "better"? 你如何定义“更好”? Shorter? 短? Using a special keyword? 使用特殊关键字? Using rarely used operators to look clever? 使用很少使用的运算符看起来很聪明? This is already just a single method call appended to your value, which even works on null values, and the logic you need can't really be expressed in a shorter way than this. 这已经只是附加到您的值的单个方法调用,它甚至可以在空值上工作,并且您所需的逻辑无法以比此更短的方式表达。 Also, I don't know of any special syntax for it. 另外,我不知道它的任何特殊语法。

but is there anything better ? 但有什么更好的吗?

No, although I'd argue that what you describe in the question (extension methods) is absolutely fine. 不,虽然我认为你在问题中描述的内容(扩展方法)绝对没问题。 And as you describe in the question, in the other direction you have null-coalescing. 正如您在问题中描述的那样,在另一个方向上,您具有无效合并。

Declare your own static method : 声明自己的静态方法:

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

Doing

MyHelper.NullIfEmpty(value) is not uglier than a call to a static method of string type... And it seems cleaner than writing "string.IsNullOrEmpty( tbCustomerId.Text)?null:tbCustomerId.Text" each time. MyHelper.NullIfEmpty(value)并不比调用字符串类型的静态方法更糟糕......而且它似乎比每次写入“string.IsNullOrEmpty(tbCustomerId.Text)?null:tbCustomerId.Text”更清晰。

Starting with your string 从你的字符串开始

string myString = "";

Write a method that converts blank to null 编写一个将blank转换为null的方法

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

Then wrap in the method and call it back with the same syntax you'd expect in SQL 然后在方法中包装并使用您在SQL中期望的相同语法将其回调

NullIf(myString);

Is it not what you directly asked, but one way to achieve what you are trying to do (pass a null value to SQL for a string if the string's value is empty) is use an if-statement to check the length of the string value being passed during the SQL Query parameter assignment (eg Parameters.AddWithValue("@parameter", mySqlValue) ):这不是您直接询问的,而是实现您想要做的事情的一种方法(如果字符串的值为空,则将空值传递给 SQL 以获取字符串)是使用 if 语句来检查字符串值的长度在 SQL Query 参数分配期间传递(例如Parameters.AddWithValue("@parameter", mySqlValue) ):

if (mySqlValue.Length > 0) {
    SqlCommand.Parameters.AddWithValue("@mySqlValue", mySqlValue);
}
else {
    SqlCommand.Parameters.AddWithValue("@mySqlValue", DBNull.Value);
}

where SqlCommand is the variable in a using statement that utilizes a parameterized SQL Query and a pre-established SQL connection/connection string.其中SqlCommand是使用参数化 SQL 查询和预先建立的 SQL 连接/连接字符串的using语句中的变量。

It's not an elegant solution, but it works (and doesn't require that you write an extension method).这不是一个优雅的解决方案,但它可以工作(并且不需要您编写扩展方法)。

If you want to return an empty string as null automatically when deserializing json:如果你想在反序列化 json 时自动返回一个空字符串作为 null:

public partial class MyClass
{
    string sample;
    [JsonProperty("myProperty")]
    public string MyProperty
    {
        get { return sample; }
        set { sample = string.IsNullOrEmpty(value) ? null : value; }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM