为什么我不能写Nullable< Nullable< int>&gt ;? [英] Why can't I write Nullable<Nullable<int>>?

查看:92
本文介绍了为什么我不能写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 ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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