C# 程序的常规结构
C# 程序由一个或多个文件组成。 每个文件都包含零个或多个命名空间。 命名空间包含类、结构、接口、枚举和委托或其他命名空间等类型。 下面的示例是包含所有这些元素的 C# 程序的框架。
using System;
Console.WriteLine("Hello world!");
namespace YourNamespace
{
class YourClass
{
}
struct YourStruct
{
}
interface IYourInterface
{
}
delegate int YourDelegate();
enum YourEnum
{
}
namespace YourNestedNamespace
{
struct YourStruct
{
}
}
}
前面的示例对程序的入口点使用 顶级语句。 只有一个文件可以有顶级语句。 程序的入口点是该文件中的第一行程序文本。 在本例中,该值为 Console.WriteLine("Hello world!");
。
还可以创建一个名为 Main
的静态方法作为程序的入口点,如以下示例所示:
// A skeleton of a C# program
using System;
namespace YourNamespace
{
class YourClass
{
}
struct YourStruct
{
}
interface IYourInterface
{
}
delegate int YourDelegate();
enum YourEnum
{
}
namespace YourNestedNamespace
{
struct YourStruct
{
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello world!");
}
}
}
在这种情况下,程序将从 Main
方法的第一行开始,也就是 Console.WriteLine("Hello world!");
。
相关部分
在基本原理指南的 类型 部分中了解这些程序元素: