什么是用C#可空类型? [英] What is nullable type in c#?

查看:138
本文介绍了什么是用C#可空类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们要使用可为空在C#.NET类型?可能任何一个请例子来说吧。

when we have to use nullable type in C#.net? could any one please explain with example.

推荐答案

可空类型(当使用可空类型)是可以取空值作为值类型。它的默认值是这意味着你没有将值分配给它。值类型的例子是整数,浮点,双,日期时间等,这些类型都有这些默认

Nullable types (When to use nullable types) are value types that can take null as value. Its default is null meaning you did not assign value to it. Example of value types are int, float, double, DateTime, etc. These types have these defaults

int x = 0;
DateTime d = DateTime.MinValue;
float y = 0;

有关可为空的替代品的任何上述的defualt是空

For Nullable alternatives, the defualt of any of the above is null

int? x = null; //no value
DateTime? d = null; //no value

这使得他们表现得像引用类型例如对象,字符串

This makes them behave like reference types e.g. object, string

string s = null;
object o = null;

其值从数据库中,当值从表中返回的时候都非常有用的是 NULL 。想象一下,在你的数据库表中的整数值,可以是NULL,这样只能重新用 0 psented $ P $如果C#变量不能为空 - 定期整数

They are very useful when dealing with values from database, when values returned from your table is NULL. Imagine an integer value in your database table that could be NULL, such can only be represented with 0 if the c# variable is not nullable - regular integer.

此外,可想而知其价值才明确在今后的实际时间结束日期列。这可以被设置为NULL在数据库中,但你需要一个可空类型来存储在C#

Also, imagine an EndDate column whose value is not determined until an actual time in future. That could be set to NULL in the DB but you'll need a nullable type to store that in C#

DateTime StartDate = DateTime.Today;
DateTime EndDate? = null; //we don't know yet

这篇关于什么是用C#可空类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆