[英]How to handle default values for null variables?
In javascript I can do this 在JavaScript我可以做到这一点
var value = obj.A || 3;
which means, if obj.A
is null or undefined or empty, then use 3 instead. 这意味着,如果obj.A
为null或未定义或为空,则使用3代替。
How can I do that in c#? 我该如何在C#中做到这一点? Or is this the best way in c#? 还是这是C#中最好的方法?
int value = obj.A == null ? 3 : obj.A;
You can do this using null propagation ?.
您可以使用null传播?.
进行此操作?.
and the null coalescing operator ??
和空合并运算符??
. 。
var value = obj?.A ?? 3;
The first one says "if obj is null, ignore A and just use null". 第一个说“如果obj为null,则忽略A并仅使用null”。 The second one says "if the left-hand side is null, use the right hand side" 第二个说“如果左侧为空,则使用右侧”
... if obj.A is null or undefined or empty, then use 3 instead. ...如果obj.A为null或未定义或为空,则改用3。
c# has no concept of undefined
. C#没有undefined
概念。 There is not much you can do about this, if you want an equivalent you would have to create some sort of generic type wrapper but I would advise against it. 您对此无能为力,如果您想要一个等效的容器,则必须创建某种通用类型包装器,但我建议您不要这样做。
There is also no native truthy
check (which is what you are actually referring to when you wrote "empty") in c# like there is in javascript. 像javascript中一样,在c#中也没有本机的truthy
检查(这是您在编写“空”时实际上指的是什么)。 You would have to build your own method or extension method or add an additional check against the default value in comparison that you want to do. 您将必须构建自己的方法或扩展方法,或者对要进行比较的默认值添加其他检查。
class Temp
{
public int? A {get;set;}
}
public static void Main()
{
Temp obj = new Temp();
int resultingValue1 = (obj.A == null || obj.A == default(int)) ? 3 : (int) obj.A;
// or
int resultingValue2 = obj.A.IsNullEmpty() ? 3 : (int) obj.A;
}
public static class Extensions
{
public static bool IsNullEmpty<T>(this T valueToCheck)
{
return valueToCheck == null || EqualityComparer<T>.Default.Equals(valueToCheck, default(T));
}
}
See also Marc Gravell's answer Null or default comparison of generic argument in C# 另请参见Marc Gravell的答案Null或C#中泛型参数的默认比较
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.