System.Nullable<T> int?

本文介绍了C#中的可空类型概念,详细解释了如何使用Nullable<T>来为值类型添加null能力,这对于处理数据库中可能未赋值的字段特别有用。
C#中怎么也引入了这样一个概念呢——“空属类型”,定义在值类型上,从此值类型摇身一变,也可以为空了,其实这个“空”也不是“真空”,怎么听起来这么矛盾,直观理解,“空Null”本身也是值的一种,可以被赋给值类型的变量了,实现这个想法和泛型有着不解之源:

.空属类型允许一个值类型具有“空值”意义,从而方便很多场合的运算,如数据库的空字段。

.空属类型实际上是一个泛型类型System.Nullable<T>。

.空属类型的基础类型就是System.Nullable<T>的类型参数,其中T必须为值类型。

.空属类型如果值不为空,可以运用同样的基础类型所具有的运算,如+, - , *, /

.空属类型的HasValue 属性用来判断类型是否为空,如果不为空,则可以通过Value属性来获取它的基础

类型的值。

1.声明方式:

int? i;//相当于 System.Nullable<int> i;注意这里的问号修饰符

2.赋值:

i = 2;//相当于i = new System.Nullable<int>(i)

3.简单类型和空属类型判等

int i = 11;

int? x= 11;

x.Equals(i) //结果如何呢其实为true

但想一想不对劲啊,如果取一下它们的类型:

i.GetType() //int 而

x.GetType() // System.Nullable<int> 应该不等啊,其实System.Nullable<T>中对Equals重载:

HasValue属性为 false,并且 other 参数为 空引用。即,根据定义,两个 null 值相等。

- 或 -

HasValue 属性为 true,并且 Value 属性返回的值等于 other 参数

所以它们相等

4.对它们转型为Object再判等

object obj1 = i;

object obj2 = x;

x.Equals(i);//这时结果一定为False

可空类型是 System.Nullable 结构的实例。可空类型可以表示其基础值类型正常范围内的值,再加上一个 null 值。例如,Nullable<Int32>,读作“可空的 Int32”,可以被赋值为 -2147483648 到 2147483647 之间的任意值,也可以被赋值为 null 值。Nullable<bool> 可以被赋值为 true 或 false,或 null。在处理数据库和其他包含可能未赋值的元素的数据类型时,将 null 赋值给数值类型或布尔型的功能特别有用。例如,数据库中的布尔型字段可以存储值 true 或 false,或者,该字段也可以未定义。

可空类型概述

可空类型具有以下特性:

可空类型表示可被赋值为 null 值的值类型变量。无法创建基于引用类型的可空类型。(引用类型已支持 null 值。)。

语法 T? 是 System.Nullable<T> 的简写,此处的 T 为值类型。这两种形式可以互换。

为可空类型赋值与为一般值类型赋值的方法相同,如 int? x = 10; 或 double? d = 4.108;。

如果基础类型的值为 null,请使用 System.Nullable.GetValueOrDefault 属性返回该基础类型所赋的值或默认值,例如 int j = x.GetValueOrDefault();

请使用 HasValue 和 Value 只读属性测试是否为空和检索值,例如 if(x.HasValue) j = x.Value;

如果此变量包含值,则 HasValue 属性返回 True;或者,如果此变量的值为空,则返回 False。

如果已赋值,则 Value 属性返回该值,否则将引发 System.InvalidOperationException。

可空类型变量的默认值将 HasValue 设置为 false。未定义 Value。

An unhandled exception occurred while processing the request. SqlNullValueException: Data is Null. This method or property cannot be called on Null values. Microsoft.Data.SqlClient.SqlBuffer.ThrowIfNull() Stack Query Cookies Headers Routing SqlNullValueException: Data is Null. This method or property cannot be called on Null values. Microsoft.Data.SqlClient.SqlBuffer.ThrowIfNull() Microsoft.Data.SqlClient.SqlBuffer.get_Int32() Microsoft.Data.SqlClient.SqlDataReader.GetInt32(int i) lambda_method372(Closure , QueryContext , DbDataReader , ResultContext , SingleQueryResultCoordinator ) Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable<T>+Enumerator.MoveNext() Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList.GetListItemsWithValueField() Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList.GetEnumerator() System.Collections.Generic.List<T>..ctor(IEnumerable<T> collection) System.Linq.Enumerable.ToList<TSource>(IEnumerable<TSource> source) Microsoft.AspNetCore.Mvc.ViewFeatures.DefaultHtmlGenerator.GenerateGroupsAndOptions(string optionLabel, IEnumerable<SelectListItem> selectList, ICollection<string> currentValues) Microsoft.AspNetCore.Mvc.ViewFeatures.DefaultHtmlGenerator.GenerateSelect(ViewContext viewContext, ModelExplorer modelExplorer, string optionLabel, string expression, IEnumerable<SelectListItem> selectList, ICollection<string> currentValues, bool allowMultiple, object htmlAttributes) Microsoft.AspNetCore.Mvc.TagHelpers.SelectTagHelper.Process(TagHelperContext context, TagHelperOutput output) Microsoft.AspNetCore.Razor.TagHelpers.TagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output) Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.RunAsync(TagHelperExecutionContext executionContext) AspNetCoreGeneratedDocument.Views_People_Create.<ExecuteAsync>b__20_0() Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.GetChildContentAsync(bool useCachedResult, HtmlEncoder encoder) Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output) Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.<RunAsync>g__Awaited|0_0(Task task, TagHelperExecutionContext executionContext, int i, int count) AspNetCoreGeneratedDocument.Views_People_Create.ExecuteAsync() in Create.cshtml + Layout = "~/Views/Shared/_Layout.cshtml"; Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context) Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, bool invokeViewStarts) Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context) Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode) Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode) Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ActionContext actionContext, IView view, ViewDataDictionary viewData, ITempDataDictionary tempData, string contentType, Nullable<int> statusCode) Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor.ExecuteAsync(ActionContext context, ViewResult result) Microsoft.AspNetCore.Mvc.ViewResult.ExecuteResultAsync(ActionContext context) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|30_0<TFilter, TFilterAsync>(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext<TFilter, TFilterAsync>(ref State next, ref Scope scope, ref object state, ref bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters() Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync() Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) Program+<>c+<<<Main>$>b__0_3>d.MoveNext() in Program.cs + await next(); Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context) Show raw exception details
最新发布
10-09
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值