簡體   English   中英

“如果此參數為null,則自動返回null”的語法糖

[英]Syntactic sugar for “If this parameter is null, automatically return null”

當特定參數為null時,是否有語法糖返回null的情況? 是否存在?

public DataObj GetMyData(DataSource source?null, User currentUser?null, string path) {
    // Code starts here. source and currentUser are not null.
}

或這個

public DataObj GetMyData(DataSource source!, User currentUser!, string path) {
    // Code starts here. source and currentUser are not null.
}

因此,如果source或currentUser為null而不需要執行該方法,則上面的方法將返回null,但是如果僅路徑為null,則它將執行。

public DataObj GetMyData(DataSource source, User currentUser, string path) {
    if (source == null || currentUser == null)
    { 
        return null;
    }
    // The rest of your code here
}

您也可以使用ArgumentNullExceptions,但是隨后您將在其他地方創建其他異常處理工作,尤其是在可以使用null參數的情況下,但是您不會從中獲得任何值。

C#6提出了空傳播運算符 ? 那將變成:

double? minPrice = null;
if (product != null
    && product.PriceBreaks != null
    && product.PriceBreaks[0] != null)
{
  minPrice = product.PriceBreaks[0].Price;
}

變成:

var minPrice = product?.PriceBreaks?[0]?.Price;

不,沒有語法糖可以返回null。

我認為存在的最接近的東西是對可空值的操作:

int? Add(int? l, int? r)
{
    return l + r;  
}

如果任何一個操作數都沒有值,將給出“ HasValue = false”。

您可能還想讀一讀“ Maybe monad”,它與您要查找的內容非常接近-即Monads的Marvels試圖用C#解釋一個(空值是其中的一個例子,但僅適用於值類型)。

如果您發現自己做了幾次,那么將其放入通用方法中將是很有意義的。 該方法可以進行檢查,它將使用一個函數,該函數將在檢查參數的空值之后執行實際操作。

public T OperateIfNotNull<T, V1, V2>(V1 arg1, V2 arg2, string path, Func<V1, V2, string, T> operation) where T : class
{
    if ((arg1 == null) || (arg2 == null) || string.IsNullOrWhiteSpace(path))
        return null;

    return operation(arg1, arg2, path);

}

暫無
暫無

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

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