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!");
。
表达式和语句
C# 程序是使用 表达式 和 语句生成的。 表达式生成值,语句执行作:
表达式是计算结果为单个值的值、变量、运算符和方法调用的组合。 表达式生成结果,可在预期值的位置使用。 以下示例是表达式:
-
42
(文本值) -
x + y
(算术运算) -
Math.Max(a, b)
(方法调用) -
condition ? trueValue : falseValue
(条件表达式) -
new Person("John")
(对象创建)
语句是执行作的完整指令。 语句不返回值;相反,它们控制程序流、声明变量或执行作。 以下示例是语句:
-
int x = 42;
(声明声明) -
Console.WriteLine("Hello");
(表达式语句 - 包装方法调用表达式) -
if (condition) { /* code */ }
(条件语句) -
return result;
(return 语句)
关键区别:表达式的计算结果为值,而语句执行作。 某些构造(如方法调用)可以是两者。 例如, Math.Max(a, b)
是一 int result = Math.Max(a, b);
个表达式,当单独写入 Math.Max(a, b);
时,它将成为表达式语句。
有关语句的详细信息,请参阅 语句。 有关 expression-bodied 成员和其他表达式功能的信息,请参阅 Expression-bodied 成员。
相关部分
在基本原理指南的 类型 部分中了解这些程序元素: