繁体   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