本文介绍了Nullable< int?>不可能,为什么不呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

打扰一下,如果这是一个愚蠢的问题,我试图更好地理解.Net中的Nullable类型。

Excuse me if its a silly question, I am trying to get a better understanding of Nullable types in .Net.

从我从Microsoft源代码中注意到的(使用ReSharper),我知道Nullable是一个结构,而T必须是一个结构

From what i notice from Microsoft source code (using ReSharper), I understand that Nullable is a struct and T needs to be a struct

public struct Nullable<T> where T : struct

现在,我试图做这样的事情

Now, I tried to do something like this

public struct CustomNullable<T> where T : struct
{
}
public class CustomNullableClass<T> where T : struct
{
}

当我出现错误时编译:

  Nullable<int?> a = null;
  Nullable<Nullable<int>> a1 = null;

对于上面提到的代码,我得到一个错误只有非空值类型可以作为系统的基础.nu​​llable,但是在Nullable类型中如何实施?

For the above mentioned code I get an error 'Only non-nullable value types could be underlying of System.Nullable', but how is this enforced in the Nullable type ?

对于

   CustomNullable<int?> a2 = null;
   CustomNullableClass<int?> a3 = null;

我收到一个错误信息:类型System.Nullable必须是不可为null的值类型才能使用它作为参数T'。

I get an error 'The type System.Nullable must be non-nullable value type in order to use it as parameter T '.

我现在有点困惑,有人可以帮助我了解发生了什么还是我不了解什么?

I am bit confused now, can some one help me understand whats going on or have I not understood something ?

非常感谢。

编辑:
如果结构是值类型并且值类型不能为null,如何Nullable可以作为结构吗?

If structs are value types and value types can't be null, how can a Nullable be a struct?

贷方:支出者

推荐答案

实际上,这是某个地方的内部黑客在C#编译器中(猜测)。您不能在自己的类中复制它。如果您使用完全相同的IL制作自己的类型,它将强制执行该附加的隐藏约束。

Actually, it's an internal hack somewhere in the C# compiler (guessing). You cannot replicate it in your own classes. If you make your own type, using the exact same IL, it will not enforce that additional hidden constraint.

这篇关于Nullable&lt; int?&gt;不可能,为什么不呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-02 00:56