当前位置:网站首页>C nullable type
C nullable type
2022-07-07 05:40:00 【Bommy games】
List of articles
One 、 Why do you need nullable types
- We all know that numerical fields in the database are nullable , For example, a certain Int Field , It can have value or no value , We need to read this field and save it in a Int In the type variable , We must consider the situation that it has no value . This is the time , You need to implement it with the help of nullable types .
- Here is an example : Java Of java.util.Date Class is a reference type , Therefore, this type of variable can be set to null, however CLR Of System.DateTime Fixed value type ,DateTime Variables can never be set to null . If you use Java Write applications that want to run CLR Of Web Service exchange date / Time , So once Jaya Program send null There's something wrong with the reception , because CLR I don't know how to express nul , I don't know how to operate it .
- Often, sometimes when we develop , I hope not initializing a value is different from initializing , The previous practice is to agree on a very special value , Then judge whether it is equal to decide whether to assign a value .
Two 、System.Nullable< T > Source code
First show the source code :
Source code address :https://referencesource.microsoft.com/#mscorlib/system/nullable.cs,ffebe438fd9cbf0e
public struct Nullable<T> where T : struct
{
private bool hasValue;
internal T value;
[System.Runtime.Versioning.NonVersionable]
public Nullable(T value) {
this.value = value;
this.hasValue = true;
}
public bool HasValue {
[System.Runtime.Versioning.NonVersionable]
get {
return hasValue;
}
}
public T Value {
get {
if (!hasValue) {
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NoValue);
}
return value;
}
}
[System.Runtime.Versioning.NonVersionable]
public T GetValueOrDefault() {
return value;
}
[System.Runtime.Versioning.NonVersionable]
public T GetValueOrDefault(T defaultValue) {
return hasValue ? value : defaultValue;
}
public override bool Equals(object other) {
if (!hasValue) return other == null;
if (other == null) return false;
return value.Equals(other);
}
public override int GetHashCode() {
return hasValue ? value.GetHashCode() : 0;
}
public override string ToString() {
return hasValue ? value.ToString() : "";
}
[System.Runtime.Versioning.NonVersionable]
public static implicit operator Nullable<T>(T value) {
return new Nullable<T>(value);
}
[System.Runtime.Versioning.NonVersionable]
public static explicit operator T(Nullable<T> value) {
return value.Value;
}
}
According to the code above , You can see Nullable The template is also a structure , Value type , Lightweight, too . It's just an addition bool hasValue, This value is set to true. Then if you get value Words , If there is no structure , Will throw an exception .
therefore , Construct an nullable int, Can write :
using System;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
Nullable<int> x = 5;
Nullable<int> y = null;
Console.WriteLine($"x hasvalue : {x.HasValue} Value: {x.Value}");
Console.WriteLine($"y hasvalue : {y.HasValue} Value: {y.GetValueOrDefault()}");
}
}
}
give the result as follows :
3、 ... and 、c# Support for nullable types
Although declare a Nullable Templates can be nullable , But officials still find it troublesome to write , therefore c# 2.0 Later, support for nullable types was added at the language level .
C# Allow to use ? Notation to declare :
int? x1 = 5;
int? y1 = null;
stay c# in int? Is equal to Nullable< T >
Allow operators to be applied to nullable instances :
using System;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
int? x = 5;
int? y = null;
// One yuan
x++;
y = -y;
// binary
x += 3;
y += 3;
// Equality
if (x == y)
{
}
// Compare
if (x < y)
{
}
}
}
}
In all operations , As long as a value is null So the result is null
3、 ... and 、c# Empty join operator of
c# The geotechnical engineer made a “ null-coalescing operator ( null - coalescing operator ), namely ?? The operator , It takes two operands . If the operand on the left is not nul , Just return the value of this operand . If the operands on the left are null , Just return the value of the operand on the right . Use the empty join operator , You can easily set the default value of variables .
One advantage of the empty operator is , It can be used for reference types , It can also be used for nullable types . The following code demonstrates how to use ?? The operator :
using System;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
int? x = null;
int? y = x.HasValue ? x : 123;
int? z = x ?? 123;
}
}
}
In the above code ,z The initialization , Equivalent to y The initialization , But it's simpler .
Four 、 Empty type packing and unpacking :
using System;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
int? x = null;
object o = x;
Console.WriteLine($"o is null ? {o == null}");
x = 5;
o = x;
Console.WriteLine($"o is null ? {o == null}");
}
}
}

From the above results, we can see that when packing, we need to see whether the nullable type is null, If it is empty, packing operation will not occur ,object Still let be null.
using System;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
object o = 5;
int? x = (int?)o; // 5
int y = (int)o; // 5
Console.WriteLine($"x: {x.Value} y {y}");
o = null;
int? x1 = (int?)o; // null
int y1 = (int)o; //System.NullReferenceException:“Object reference not set to an instance of an object.”
Console.WriteLine($"x1: {x1.Value} y1 {y1}");
}
}
}
You can see from the code above , Unpacking for non null Objects can be converted to int perhaps int?, But for null object , If it turns into int An exception will be thrown .
5、 ... and 、 Nullable type GetType()
stay Nullable< T > Object GetType() Method ,CLR Actually, I will lie and say that the type is T, instead of Nullable< T >.
So run the following code :
int? x = 5;
Console.WriteLine($"x.GetType() : {x.GetType()}");
result :
summary
Null type , On the one hand, it is compatible with some business pairs null Value type requirements , On the one hand, it improves the brevity of the code . Therefore, it can be used properly when writing code .
边栏推荐
- High voltage leakage relay bld-20
- [论文阅读] Semi-supervised Left Atrium Segmentation with Mutual Consistency Training
- How Alibaba cloud's DPCA architecture works | popular science diagram
- Preliminary practice of niuke.com (9)
- Where is NPDP product manager certification sacred?
- 导航栏根据路由变换颜色
- Flink SQL 实现读写redis,并动态生成Hset key
- Pytest testing framework -- data driven
- Jhok-zbl1 leakage relay
- Egr-20uscm ground fault relay
猜你喜欢

Mapbox Chinese map address

5. Data access - entityframework integration

Senior programmers must know and master. This article explains in detail the principle of MySQL master-slave synchronization, and recommends collecting
![[binary tree] binary tree path finding](/img/34/1798111e9a294b025806a4d2d5abf8.png)
[binary tree] binary tree path finding

Leakage relay jelr-250fg

照片选择器CollectionView

JVM (XX) -- performance monitoring and tuning (I) -- Overview

Use, configuration and points for attention of network layer protocol (taking QoS as an example) when using OPNET for network simulation

导航栏根据路由变换颜色

随机生成session_id
随机推荐
nodejs获取客户端ip
Is the human body sensor easy to use? How to use it? Which do you buy between aqara green rice and Xiaomi
Where is NPDP product manager certification sacred?
A cool "ghost" console tool
Mybaits multi table query (joint query, nested query)
Senior programmers must know and master. This article explains in detail the principle of MySQL master-slave synchronization, and recommends collecting
淘寶商品詳情頁API接口、淘寶商品列錶API接口,淘寶商品銷量API接口,淘寶APP詳情API接口,淘寶詳情API接口
高级程序员必知必会,一文详解MySQL主从同步原理,推荐收藏
Let f (x) = Σ x^n/n^2, prove that f (x) + F (1-x) + lnxln (1-x) = Σ 1/n^2
JVM (XX) -- performance monitoring and tuning (I) -- Overview
ForkJoin最全详解(从原理设计到使用图解)
Unity keeps the camera behind and above the player
High voltage leakage relay bld-20
English grammar_ Noun possessive
5. Data access - entityframework integration
How can project managers counter attack with NPDP certificates? Look here
[JS component] date display.
基于NCF的多模块协同实例
拼多多新店如何获取免费流量,需要从哪些环节去优化,才能有效提升店内免费流量
【js组件】date日期显示。