【问题标题】:Why Nullable<int> can't compile but int? does without 'using System;'为什么 Nullable<int> 不能编译但 int?没有'使用系统;'
【发布时间】:2009-09-03 03:42:11
【问题描述】:

在.Net 2中,代码:

namespace ns
{
    class Class1
    {
        Nullable<int> a;
    }
}

不编译并报错:

找不到类型或命名空间名称“Nullable”(您是否缺少 using 指令或程序集引用?)

缺少using System;,但此代码:

namespace ns
{
    class Class1
    {
        int? a;
    }
}

编译。

谁能解释一下原因?

【问题讨论】:

    标签: c# .net compiler-construction


    【解决方案1】:

    T? 语法由编译器通过直接引用类型转换为System.Nullable&lt;T&gt;,而不是通过检查范围内的usings。你可以类似地写这个,编译器会成功:

    System.Nullable<int> a;
    

    【讨论】:

      【解决方案2】:

      我相信int?是

      的别名
      System.Nullable<System.Int32>
      

      因为指定了完整的类型名称,所以没有理由添加using 指令。

      【讨论】:

        【解决方案3】:

        ?是一种语言结构,而 System.Nullable 是一个类 - 因为它位于 System 命名空间中,所以您必须将其导入文件中(或者更常见的是,将其显式导入整个项目作为项目属性/配置的一部分) .

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-06-22
          • 2015-11-07
          • 2010-09-06
          • 2022-11-14
          • 2010-11-05
          相关资源
          最近更新 更多