简体   繁体   English

“如果此参数为null,则自动返回null”的语法糖

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

Is there any case for syntactic sugar that returns null when a specific parameter is null? 当特定参数为null时,是否有语法糖返回null的情况? Does this exist? 是否存在?

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

or this 或这个

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

So the above would return null if either the source or currentUser were null without having to execute the method, but it would execute if only the path was 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
}

You could also use ArgumentNullExceptions, but then you are creating additional exception handling work elsewhere especially if null parameters are ok, but you don't get a value from it. 您也可以使用ArgumentNullExceptions,但是随后您将在其他地方创建其他异常处理工作,尤其是在可以使用null参数的情况下,但是您不会从中获得任何值。

C# 6 is proposing a null propagation operator ? C#6提出了空传播运算符 ? that will turn: 那将变成:

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

into: 变成:

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

No, there is no syntactic sugar to return null. 不,没有语法糖可以返回null。

I think the closest thing that exist is operations on nullable values: 我认为存在的最接近的东西是对可空值的操作:

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

Will give you "HasValue = false" if either operand does not have value. 如果任何一个操作数都没有值,将给出“ HasValue = false”。

You may also want to read about "Maybe monad" which is very close to what you are looking for - ie Marvels of Monads tries to explain one in C# (nullable values is example on one, but apply only to value types). 您可能还想读一读“ Maybe monad”,它与您要查找的内容非常接近-即Monads的Marvels试图用C#解释一个(空值是其中的一个例子,但仅适用于值类型)。

If it is something you find yourself doing a few times, it would make sense to put it into a generic method. 如果您发现自己做了几次,那么将其放入通用方法中将是很有意义的。 That method can do the checks and it will use a function that will do the actual operation after checking for the nulls on the arguments. 该方法可以进行检查,它将使用一个函数,该函数将在检查参数的空值之后执行实际操作。

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