简体   繁体   English

与变量本身的空合并运算符

[英]Null coalescing operator with the variable itself

Is there any way of reduce the null coalescing operator expression when the variable we check is the one we will assign if it's not null?当我们检查的变量是我们将要分配的变量时,如果它不为空,是否有任何方法可以减少空合并运算符表达式?

Example:例子:

DateTime? date1 = DateTime.Parse("11/05/1990");
DateTime? date2 = DateTime.Now;
date1 = date1 ?? date2;

For instance, something like that:例如,这样的事情:

date1 = ?? date2;

I know that's not a big deal but I'm curious.我知道这没什么大不了的,但我很好奇。

No, this does not exist in C#.不,这在 C# 中不存在。

You can find the list of operators in https://msdn.microsoft.com/nl-nl/library/6a71f45d.aspx .您可以在https://msdn.microsoft.com/nl-nl/library/6a71f45d.aspx 中找到运算符列表。

But isn't date1 = date1 ?? date2但不是date1 = date1 ?? date2 date1 = date1 ?? date2 short enough already ? date1 = date1 ?? date2已经够短了吗?

No. If there was then:不。如果有的话:

_field ?? (_field = CalculateFieldValue());

wouldn't be so common in memoised properties.在记忆属性中不会那么常见。

Starting from C# 8.0 , the null-coalescing assignment operator, ??= , is available.C# 8.0 开始,可以使用空合并赋值运算符??=

So it would be所以它会

date1 ??= date2;

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

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