---
title: "c#教程第一课:简单的欢迎程序"
author: "kanglecjr"
date: "2009-04-14T04:53:18Z"
tags: ["C", "C#", "C++", "工作"]
slug: "c"
draft: false
lastmod: "2009-04-14T04:53:18Z"
id: 366885
url: "https://kanglecjr.iteye.com/blog/366885"
---

本节程要达到如下几个目的：
1.理解一个C#程序的基本结构。

2.初步了解"名称空间"的概念。

3.初步了解"类"的概念。

4.了解"Main"方法所做的工作。

5.学会如何读取命令行输入信息。

6.学会使用控制台输入/输出 (I/O)语句。

1.清单1-1. 一个简单的欢迎程序Welcome.cs 

```c#
// Namespace Declaration
using System;
// Program start class
class WelcomeCSS {
// Main begins program execution.
public static void Main() {
// Write to console
Console.WriteLine("Welcome to the C# Station Tutorial!");
}
}
```


2.清单1-2. 读取命令行输入信息的程序NamedWelcome.cs

```c#
// Namespace Declaration
using System;
// Program start class
class NamedWelcome {
// Main begins program execution.
public static void Main(string[] args) {
// Write to console
Console.WriteLine("Hello， {0}!"， args[0]);
Console.WriteLine("Welcome to the C# Station Tutorial!");
}
}
```

该语句中的参数表同以往的写法不同，其中有个格式字符串"{0}" 参数。 格式串中的第一个参数从数字0开始，第二个参数从数字1开始，依此类推。 "{0}" 参数意味着双引号后面的参数值将会输出到该位置。

> >Hello， Joe!
> >Welcome to the C# Station Tutorial!


3.清单1-3. 交互式处理输入信息的程序 InteractiveWelcome.cs

```c#
// Namespace Declaration
using System;
// Program start class
class NamedWelcome {
// Main begins program execution.
public static void Main() {
// Write to console/get input
Console.Write("What is your name?: ");
Console.Write("Hello， {0}! "， Console.ReadLine());
Console.WriteLine("Welcome to the C# Station Tutorial!");
}
}
```

说明 

这一次，"Main"方法没有用到任何参数，但现在程序中有了三条语句，前面两条语句不同于第三条语句，它们是："Console.Write(...)"而不是 "Console.WriteLine(...)"。区别是："Console.Write(...)"语句把信息输出到控制台，之后光标停留在同一行，而"Console.WriteLine(...)"把信息输出，之后换行。

第一条语句仅仅输出"What is your name?: "到控制台。

第二条语句要等到其参数被适当地处理之后，才会输出信息。 格式串后面的第一个参数是："Console.ReadLine()"。这就使得程序要等待用户在控制台输入信息，输入信息以回车或者换行结束。该方法的返回值替换了格式串中的"{0}"参数，并输出到控制台上。

最后一个语句也用来输出信息到控制台，这一点我们在前面已经介绍过。一旦运行了程序"InteractiveWelcome"，其输出结果为：

> >What is your Name? 
> >Hello， ! Welcome to the C# Station Tutorial!

小结
到现在为止，你已经了解了C#程序的基本结构，名称空间和类。你还了解到"Main"方法是C# 程序的入口，并学会了如何捕捉命令行的输入信息，以及如何进行交互式的I/O操作。