在学习 c# 编程语言的基本构建块之前,先来看一下最简单的 c# 程序结构,以便将其作为即后续章节的学习参考。
这个简单的 c# 程序由以下部分组成:
下面让我们来看一个打印“hello world”的简单代码:
using system;
namespace helloworldapplication{
class helloworld{
static void main(string[] args){
/* my first program in c# */
console.writeline("hello world");
console.readkey();
}
}
}
当编译和执行这段代码时,它产生以下结果:
hello world
下面来看看给定的示例程序的各个部分:
using system;
- using
关键字用于在程序中包含system
命名空间。程序中通常有多个using
语句。namespace
)声明。namespace
是类的集合。 helloworldapplication
命名空间包含helloworld
类。helloworld
类包含程序使用的数据和方法定义。类通常包含多种方法。方法定义类的行为。 但是这定义的helloworld
类只有一个main
方法。main
方法,它是所有 c# 程序的入口点。main
方法执行该类的操作。/*...*/
之间的内容。main
方法的具体功能实现,这里只是使用语句console.writeline(“hello world”)
指定其行为;writeline
是在system
命名空间中定义的console
类的一个方法。此方法将消息“hello, world!”显示在屏幕上。console.readkey();
是用于使程序等待按键,并且当从visual studio .net启动程序时,它可以防止屏幕快速运行和关闭。需要注意的是:
;
)结尾。main
方法开始。如果使用visual studio.net编译和执行 c# 程序,请执行以下步骤:
"hello world"
行的命令提示符窗口。可以使用命令行(而不是visual studio ide)来编译 c# 程序:
csc helloworld.cs
,然后按enter键编译代码。helloworld.exe
可执行文件。helloworld
来执行你的程序。"hello world"
字符串了。