为什么我不能写Nullable< Nullable< int>&gt ;?

编程入门 行业动态 更新时间:2024-10-25 02:19:39
本文介绍了为什么我不能写Nullable< Nullable< int>&gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

Nullable< T> 是:

[SerializableAttribute] public struct Nullable<T> where T : struct, new()

约束其中T:struct 表示 T 只能是值类型。因此,我非常理解我无法写:

The constraint where T : struct implies that T can only be a value type. So I very well understand that I cannot write:

Nullable<string> a; //error. makes sense to me

因为 string 是一个引用类型,而不是值类型。但是我真的不明白为什么我不能写

Because string is a reference type, not a value type. But I don't really understand why can't I write

Nullable<Nullable<int>> b; //error. but why?

为什么不允许?毕竟, Nullable< int> 是一种值类型,因此,它可以是 Nullablle< T> 。

Why is it not allowed? After all, Nullable<int> is a value-type, and therefore, it can be type argument to Nullablle<T>.

当我在ideone上编译它时,会出现此错误( ideone ):

When I compiled it on ideone, it gives this error (ideone):

错误CS0453:类型'int?'必须是不可为空的值类型,以便在通用类型或方法'System.Nullable'中将其用作类型参数'T'编译失败:1个错误,0个警告

error CS0453: The type 'int?' must be a non-nullable value type in order to use it as type parameter 'T' in the generic type or method 'System.Nullable' Compilation failed: 1 error(s), 0 warnings

推荐答案

来自C#语言规范的4.1.10节:

From section 4.1.10 of the C# language spec:

相反, 不可为空的值类型 是除 System.Nullable< T> 及其速记 T?(对于任何 T ),以及任何被约束为非空值类型的类型参数(即是,任何具有 struct 约束的类型参数)。 System.Nullable< T> 类型为 T (第10.1.5节)指定值类型约束。可空类型的基础类型可以是任何非空值类型。可为空的类型的基础类型不能为可为空的类型或引用类型。例如, int ?? 和 string?是无效的类型。

A non-nullable value type conversely is any value type other than System.Nullable<T> and its shorthand T? (for any T), plus any type parameter that is constrained to be a non-nullable value type (that is, any type parameter with a struct constraint). The System.Nullable<T> type specifies the value type constraint for T (§10.1.5), which means that the underlying type of a nullable type can be any non-nullable value type. The underlying type of a nullable type cannot be a nullable type or a reference type. For example, int?? and string? are invalid types.

更多推荐

为什么我不能写Nullable&lt; Nullable&lt; int&gt;&gt ;?

本文发布于:2023-11-09 06:07:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1571589.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:amp   Nullable   lt   gt   int

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!