【问题标题】:C#: Why is there a difference between void and System.Void [duplicate]C#:为什么 void 和 System.Void 之间有区别 [重复]
【发布时间】:2012-10-17 08:34:58
【问题描述】:

可能重复:
What is System.Void?
Why not System.Void?

我注意到不允许使用typeof(System.Void)。但是typeof(void) 是允许的。 当您使用typeof(System.String)typeof(string) 时,没有区别。

为什么会这样?

【问题讨论】:

标签: c# void


【解决方案1】:

这是因为 C# 定义了别名以保持原始 C 风格。

.NET 框架使用特定的命名约定:例如,它规定类名应以大写字母开头。因此,String——它不是 C# 原生类型,而是在 System 命名空间中定义的 .NET 类——实际上称为 System.String,或者简称为 String,如果你的文件中有一个 using System;文件。

C# 将 string 定义为 System.String 的别名,以便代码看起来像在 C 和其他基于 C 的语言(C++、Java...)中的样子。我认为它更具可读性。同样,intSystem.Int32 相同。

【讨论】:

    【解决方案2】:

    void 不像 string。在 C# 中使用 void 的几乎所有情况下,编译器都会对其进行特殊处理,例如在 void-"returning" 方法中不需要 return 语句,并且不允许 @987654326带有“值”类型为void 的表达式的@ 语句。 typeof(void)void 真正被视为常规类型的少数情况之一。它是双向的:编译器可以假设任何不是void 的类型都不应该得到void 的特殊处理。允许以其他方式拼写 void 会使解释 C# 变得更加复杂,而且您没有理由需要它。

    【讨论】:

      【解决方案3】:

      string 是类System.String 的别名。

      其他别名列表

      • 对象:System.Object
      • 字符串:System.String
      • bool:System.Boolean
      • 字节:System.Byte
      • sbyte: System.SByte
      • 短:System.Int16
      • ushort:System.UInt16
      • int:System.Int32
      • uint: System.UInt32
      • 长:System.Int64
      • ulong:System.UInt64
      • 浮点数:System.Single
      • 双:System.Double
      • 十进制:System.Decimal
      • 字符:System.Char

      感谢Jon Skeet

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-16
        • 1970-01-01
        • 2013-02-20
        • 2011-04-12
        • 1970-01-01
        • 2018-03-05
        • 2010-12-21
        • 2018-03-16
        相关资源
        最近更新 更多