gpt4 book ai didi

c# - 为什么原始数据类型在不包含 System 命名空间的情况下也能工作?

转载 作者:IT王子 更新时间:2023-10-29 04:42:17 25 4
gpt4 key购买 nike

我读到所有原语都属于 System 命名空间。如果我注释掉 using System 我希望我的程序中出现构建错误,但它运行成功。这是为什么?

Attached the snap of my sample program.

最佳答案

这是因为 intSystem.Int32 的别名,并且由于“Int32”已经以其 namespace 为前缀(即“完全限定”),所以语法是合法的,无需在代码顶部指定 using System;

MSDN下面的片段描述了这个概念-

Most C# applications begin with a section of using directives. This section lists the namespaces that the application will be using frequently, and saves the programmer from specifying a fully qualified name every time that a method that is contained within is used. For example, by including the line:

using System;

At the start of a program, the programmer can use the code:

Console.WriteLine("Hello, World!");

Instead of:

System.Console.WriteLine("Hello, World!");

System.Int32(又名“int”)就是后者。这是代码中的示例 -

//using System;

namespace Ns
{
public class Program
{
static void Main(string[] args)
{
System.Int32 i = 2; //OK, since we explicitly specify the System namespace
int j = 2; //alias for System.Int32, so this is OK too
Int32 k = 2; //Error, because we commented out "using System"
}
}
}

由于第 11 行不是完全限定的/别名是完全限定的类型,using System; 需要取消注释才能使错误消失。

其他引用资料-

关于c# - 为什么原始数据类型在不包含 System 命名空间的情况下也能工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31894032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com