为什么Nullable< T>不匹配通用约束的参考类型 [英] Why does Nullable<T> not match as a reference type for generic constraints

查看:153
本文介绍了为什么Nullable< T>不匹配通用约束的参考类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Nullable类型作为可能的泛型参数?

我遇到了一个非常奇怪的东西,通用类型约束。我有这样的一个类:

  public SomeClass< T> T:class 
{
}

然而,我发现我不能像我所期望的那样使用可为null的类型:

  new SomeClass< int?>(); 

我得到一个错误,指出 int?必须是一个参考类型。 Nullable真的只是一个带有语法糖的结构,使它看起来像一个引用类型吗?

解决方案

Nullable< ; T> 是 struct (请参阅 MSDN ),但它是唯一不符合 struct struct $ c>约束。因此,当结构体时,不能使用 Nullable 作为泛型类型参数使用约束。



可空<> 合成糖。 CLR对它的一些行为有特别的支持。例如,它有特殊的拳击行为。具体来说,一个可为空的永远不会被装箱。底层价值是盒装的。如果可为空值(HasValue为false),则将其转换为空引用。另外,任何 Nullable Nullable 的转换操作符都从 T U 。这些功能是您无法在.NET 1.0 / 1.1中实现的功能。


Possible Duplicate:
Nullable type as a generic parameter possible?

I came across a very weird thing with generic type constraints. I have a class like this:

public SomeClass<T> where T:class
{
}

However, I've found I can't use nullable types as I'd expect:

new SomeClass<int?>();

I get an error that int? must be a reference type. Is Nullable really just a struct with syntactic sugar to make it look like a reference type?

解决方案

Nullable<T> is a struct (see MSDN) however it is the only struct that does not satisfy the struct constraint. Therefore, you cannot use a Nullable as a generic type parameter when either the class or struct constraints is used.

Nullable<T> is not just a struct with some syntatic sugar. It has special support in the CLR for some of its behavior. For example, it has special boxing behavior. Specifically, a nullable is never boxed. The underlying value is boxed. If the nullable is the null value (HasValue is false) then it is converted to a null reference. Also, conversion operators for any Nullable<T> to Nullable<U> are lifted from the conversions from T to U. These are features you wouldn't be able to implement yourself in .NET 1.0/1.1.

这篇关于为什么Nullable&lt; T&gt;不匹配通用约束的参考类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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