簡體   English   中英

檢查該方法是返回值還是 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) 返回 null,在這種情況下,我不想將 null 值分配給 appResponse.LogoImage,只有當 GetImage(appId) 返回一個值時,我才想分配該值。

我可以使用 If 條件檢查 GetImage(appId) 是否返回 null 然后分配值,但是我將對 GetImage() 方法進行 2 次調用,我覺得這不是一個好方法。

在一行中,我可以檢查 null 並且當它不是 null 時,然后僅將值分配給 appResponse.LogoImage?

我可以使用 If 條件檢查 GetImage(appId) 是否返回 null 然后分配值,但隨后我將對 GetImage() 方法進行 2 次調用

你為什么要叫它兩次?

這里只是一個電話:

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

您可以使用空合並運算符??

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

從文檔:

空合並運算符?? 如果不是 null,則返回其左側操作數的值; 否則,它計算右手操作數並返回其結果。 ?? 如果左側操作數的計算結果為非空,則運算符不會計算其右側操作數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM