C# ? and ?? 操作符

              DataTime ?  表示此类型可以为null,可以为其赋值为null,尤其是在数据库操作中, 比如年龄 我们会定义为 int age; 为其附默认值一般为0,但是我们一般不希望在这样,所以如果在定义时int?age;则可以为其赋值为null。

  int?与Nullable<int>一样。其定义如下:

    

public class AlterNativePriority
    {
        public string AlterNativePriorityID { get; set; }
        public string Priority { get; set; }
        public string Object { get; set; }
        public string Remark { get; set; }
        public string IsAvailable { get; set; }
        public Nullable<Int32> ChangeCount { get; set; }
        public string LastUpdatedUserID { get; set; }
        public DateTime? LastUpdatedDate { get; set; }
        public string Plant { get; set; }
    }

            ?? 运算符称作 null 合并运算符。 如果此运算符的左操作数不为 null,则此运算符将返回左操作数;否则返回右操作数.

         可以为 null 的类型可以表示类型的域中的值,或者值可以是未定义的(在这种情况下,值为 null)。 当左操作数具有一个值为 null 的可以为 null 的类型时,可以使用 ?? 运算符的语法表现力来返回适当的值(右操作数)。 如果在尝试将可以为 null 值的类型分配给不可以为 null 值的类型时没有使用 ?? 运算符,则会生成编译时错误。 如果使用强制转换,且当前未定义可以为 null 值的类型,则会引发 InvalidOperationException 异常。


参考:https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/operators/null-conditional-operator

https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/nullable-types/index


猜你喜欢

转载自blog.csdn.net/weixin_39730950/article/details/78547220