C# 检查空值的最短方法,如果不是,则分配另一个值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1120557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 08:41:10  来源:igfitidea点击:

Shortest way to check for null and assign another value if not

c#.netnullvariable-assignment

提问by Splashlin

I am pulling varcharvalues out of a DB and want to set the stringI am assigning them to as "" if they are null. I'm currently doing it like this:

我正在varchar从数据库中提取值并希望将string我分配给它们的值设置为 "" 如果它们是null. 我目前正在这样做:

if (string.IsNullOrEmpty(planRec.approved_by) == true)
  this.approved_by = "";
else
  this.approved_by = planRec.approved_by.toString();

There seems like there should be a way to do this in a single line something like:

似乎应该有一种方法可以在一行中执行此操作,例如:

this.approved_by = "" || planRec.approved_by.toString();

However I can't find an optimal way to do this. Is there a better way or is what I have the best way to do it?

但是,我找不到执行此操作的最佳方法。有没有更好的方法,或者我有什么最好的方法来做到这一点?

采纳答案by Andrew Hare

Try this:

尝试这个:

this.approved_by = IsNullOrEmpty(planRec.approved_by) ? "" : planRec.approved_by.toString();

You can also use the null-coalescing operator as other have said - since no one has given an example that works with your code here is one:

您也可以像其他人所说的那样使用空合并运算符 - 因为没有人给出适用于您的代码的示例,这里是一个:

this.approved_by = planRec.approved_by ?? planRec.approved_by.toString();

But this example only works since a possible value for this.approved_byis the same as one of the potential values that you wish to set it to. For all other cases you will need to use the conditional operator as I showed in my first example.

但此示例仅有效,因为 的可能值this.approved_by与您希望将其设置为的潜在值之一相同。对于所有其他情况,您将需要使用我在第一个示例中展示的条件运算符。

回答by Dave Ward

The coalesce operator (??)is what you want, I believe.

COALESCE操作符(??)是你想要的,我相信。

回答by JaredPar

You are looking for the C# coalesce operator: ??. This operator takes a left and right argument. If the left hand side of the operator is null or a nullable with no value it will return the right argument. Otherwise it will return the left.

您正在寻找 C# 合并运算符:??。此运算符采用左参数和右参数。如果运算符的左侧为 null 或一个没有值的可空值,它将返回正确的参数。否则它将返回左侧。

var x = somePossiblyNullValue ?? valueIfNull;

回答by Dmitri Nesteruk

My guess is the best you can come up with is

我的猜测是你能想到的最好的办法是

this.approved_by = IsNullOrEmpty(planRec.approved_by) ? string.Empty
                                                      : planRec.approved_by.ToString();

Of course since you're hinting at the fact that approved_byis an object(which cannot equal ""), this would be rewritten as

当然,由于您暗示的approved_by是一个事实object(不能等于“”),这将被重写为

this.approved_by = (planRec.approved_by ?? string.Empty).ToString();

回答by Paul Alexander

To extend @Dave's answer...if planRec.approved_by is already a string

扩展@Dave的答案......如果 planRec.approved_by 已经是一个字符串

this.approved_by = planRec.approved_by ?? "";

回答by user133371

You can also do it in your query, for instance in sql server, google ISNULLand CASEbuilt-in functions.

您也可以在查询中执行此操作,例如在 sql server、googleISNULLCASE内置函数中。

回答by Ali Humayun

I use extention method SelfChk

我使用扩展方法 SelfChk

static class MyExt {
//Self Check 
 public static void SC(this string you,ref string me)
    {
        me = me ?? you;
    }
}

Then use like

然后使用像

string a = null;
"A".SC(ref a);

回答by Malcolm

With C#6 there is a slightly shorter way for the case where planRec.approved_by is not a string:

在 C#6 中,对于 planRec.approved_by 不是字符串的情况,有一种更短的方法:

this.approved_by = planRec.approved_by?.ToString() ?? "";

回答by Ramgy Borja

Use the C# coalesce operator: ??

使用 C# 合并运算符: ??

// if Value is not null, newValue = Value else if Value is null newValue is YournullValue
var newValue = Value ?? YourNullReplacement;

回答by Hyman Miller

To assign a non-empty variable without repeating the actual variable name (and without assigning anything if variable is null!), you can use a little helper method with a Actionparameter:

要在不重复实际变量名称的情况下分配非空变量(如果变量为空,则不分配任何内容!),您可以使用一个带Action参数的小辅助方法:

public static void CallIfNonEmpty(string value, Action<string> action)
{
    if (!string.IsNullOrEmpty(value))
        action(value);
}

And then just use it:

然后只需使用它:

CallIfNonEmpty(this.approved_by, (s) => planRec.approved_by = s);