www.cftea.com

关于 CSharp 值-?. 的默认值

ITPOW2019/12/28 10:31:15

C# 中 ?. 表示对象为 null 时,取其属性也不会报错,那么对象为 null 时,取出来的属性值是什么呢?0?null?

public class C
{
    public int F1 { get; set; }
    public int? F2 { get; set; }
    public int F3 { get; set; } = 1;
    public int? F4 { get; set; } = 1;
}


C c = null;
Response.Write("f1:" + c?.F1 + "," + (c?.F1 == null) + "<br>"); // f1:,True
Response.Write("f2:" + c?.F2 + "," + (c?.F2 == null) + "<br>"); // f2:,True
Response.Write("f3:" + c?.F3 + "," + (c?.F3 == null) + "<br>"); // f3:,True
Response.Write("f4:" + c?.F4 + "," + (c?.F4 == null) + "<br>"); // f4:,True
            
C c = new C();
Response.Write("f1:" + c?.F1 + "," + (c?.F1 == null) + "<br>"); // f1:0,False
Response.Write("f2:" + c?.F2 + "," + (c?.F2 == null) + "<br>"); // f2:,True
Response.Write("f3:" + c?.F3 + "," + (c?.F3 == null) + "<br>"); // f3:1,False
Response.Write("f4:" + c?.F4 + "," + (c?.F4 == null) + "<br>"); // f4:1,False

我们可以看到,当对象为 null 时,?. 取出来的属性值是 null(并不是返回 ?. 后面的数据类型的默认值)。上面代码中,我们同时也测试了下 int? 的默认值,这个问题我们之前讨论过,请参见:关于 CSharp 值-默认值

【记忆方法】爹都 null 了,儿子能不 null?

题外:null 既不 > 0,也不 < 0,也不 == 0。

相关阅读

<<返回首页<<