空合并运算符是否将结果缓存在C#中 [英] Does null coalescing operator cache the result in c#

查看:75
本文介绍了空合并运算符是否将结果缓存在C#中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道做(myValue ?? new SomeClass())(myValue == null ? new SomeClass() : myValue)

但是出于好奇,当我调用一个函数时,性能会有所提高吗? (getResult() ?? new SomeClass()). getResult()将执行两次吗?因为我只指定了一次方法调用,所以这似乎并不直观.

But out of curiosity, is there any performance benefit when I call a function, say (getResult() ?? new SomeClass()). Will getResult() get executed twice? It seems unintuitive since I've specified the method call only once.

推荐答案

好吧,如果缓存"是指将其存储在临时变量中,那么可以.

Well, if by "caching" you mean storing it in a temporary variable, then yes.

此构造:

var result = (getResult() ?? new SomeClass());

可以被认为等同于此:

var <temp> = getResult();
if (<temp> == null)
    <temp> = new SomeClass();
result = <temp>;

这还告诉您第二部分,如果第一个操作数不是null,则根本不执行??之后的操作数.

This also tells you that the second part, the operand after ?? isn't executed at all if the first operand is not null.

因此,请回答您的具体问题:

So to answer your concrete questions:

  1. 每个操作数最多评估一次
  2. 仅当第一个操作数的值为null
  3. 时,才对第二个操作数求值
  1. Each operand is evaluated at most once
  2. The second operand is only evaluated if the first one evaluates to null

请注意,您可以将它们链接起来:

Note also that you can chain these:

var result = first() ?? second() ?? third() ?? fourth();

这将导致:

  1. 评估first()
  2. 如果first()评估为null,则评估second()
  3. 如果second()也评估为null,则评估third()
  4. 如果以上所有条件均评估为null,则最终评估为fourth
  1. Evaluates first()
  2. If first() evaluated to null, evaluates second()
  3. If second() evaluated to null as well, evaluates third()
  4. If all of the above evaluated to null, finally evaluates fourth

结果是返回的第一个(非双关语)非空值.

The result is the first (no pun intended) non-null value returned.

使用新的?.运算符,这种类型的代码将在新的C#中变得更好:

This type of code is about to get even better in new C# with the new ?. operator:

var result = first?.second?.third;

这是基本的.处理,即它将读取firstsecond成员,然后读取任何secondthird成员,但是它将在第一个null处停止,并且还将确保每个步骤仅评估一次:

This is basic . handling, ie. it will read the second member of first, and then the third member of whatever second is, but it will stop at the first null, and will also make sure to evaluate each step only once:

(obj as IDisposable)?.Dispose();

obj as IDisposable只会计算一次.

TryGetObjectToSave()?.Save();

只会调用一次TryGetObjectToSave(),并且如果返回某个内容,则将调用该内容上的Save()方法.

Will only call TryGetObjectToSave() once, and if it returns something, the Save() method on that something will be called.

这篇关于空合并运算符是否将结果缓存在C#中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆