在 C# 中是否有等价于 SQL NULLIF 的函数?

Is there an equivalent of SQL NULLIF function in c#?

C# 中是否内置了与 SQL NULLIF 等效的函数?

外观示例:

double? result
double denominator = 0;
double Numerator = 100;
result = Numerator / NullIf(denominator, 0);
result = Numerator / denominator.NullIf(0);
result = Numerator / Object.NullIf(denominator, 0);

不,但你可以创建一个。

public static Nullable<T> NullIf<T>(T first, T second) where T : struct
{
    if(first == second)
        return new Nullable<T>();
    return new Nullable<T>(first);
}

没有。但是您可以使用三元运算符来编写它的紧凑方式:

double? result
double denominator = 0;
double Numerator = 100;
result = denominator == 0 ? (double?)null : Numerator / denominator;

但是有 IFNULL 的等价物:

result = x ?? 0; 

相当于:

result = x.HasValue? x.Value : 0;

不,目前没有语言功能。

你可以很容易地得到相同的结果,或者使用三元 if:

result = Numerator / (denominator == 0 ? (double?)null : denomiantor);

或者甚至将其包装为通用函数,例如:

Nullable<T> NullIf<T>(T left, T right)
{
    return left == right ? (T?)null : left;
}

然后可以这样调用:

result = Numerator / NullIf(denominator, 0);

接受的答案给我:

Operator '==' cannot be applied to operands of type 'T' and 'T'

我的 NULLIF 工作示例:

public static T? NullIf<T>(T left, T right) where T : struct
{
    return EqualityComparer<T>.Default.Equals(left, right) ? (T?)null : left;
}

为什么我们假设此扩展方法能够知道我们的上下文中什么是 null。

这是调用它的上下文的责任。 因此,说只有一个值将被视为 null 是错误的,因为该线程中的所有响应都暗示。

public static T? NullIf<T>(this T value, Func<T,bool> isConsideredNull) 
{
        if(value == null)
        {
           return null;
        }
        return isConsideredNull(value) ? (T?)null : value;
}

我们将按以下方式使用它

string test = "NULL";

test.NullIf((x)=> x.Equals("NULL"));
test.NullIf((x)=> x == "NULL");
test.NullIf((x)=> x.Equals("NULL",StringComparison.InvariantCultureIgnoreCase));