检查该方法是否返回值或 null 并根据该值分配值

Check whether the method is returning a value or null and based on that assign the value

我有一个场景,我通过以下方式为 class 属性 赋值。

var appResponse = GetAppResponse();
appResponse.LogoImage = GetAppImage(appId);

这里的问题有时是 GetImage(appId) returns null,在那种情况下,我不想将该空值分配给 appResponse.LogoImage,只有当 GetImage(appId) returns一个值然后我只想分配那个值。

我可以使用 If 条件来检查 GetImage(appId) 是否返回 null,然后分配值,但是我将对方法 GetImage() 进行 2 次调用,这不是一个好方法我感觉。

我可以在一行中检查是否为 null,当它不为 null 时,则只将值赋给 appResponse.LogoImage?

I can use a If condition to check if GetImage(appId) is returning null or not and then assign the value, but then I will be making 2 calls to the method GetImage()

为什么要调用它两次?

这里只有一个调用:

var appResponse = GetAppResponse();
var appImage = GetAppImage(appId);
if (appImage != null) {
    appResponse.LogoImage = appImage;
}

您可以使用 null-coalescing operator??

appResponse.LogoImage = GetAppImage(appId) ?? appResponse.LogoImage;

来自文档:

The null-coalescing operator ?? returns the value of its left-hand operand if it isn't null; otherwise, it evaluates the right-hand operand and returns its result. The ?? operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-null.