C# 程序通常由 命名空间(Namespace) 、类(Class) 、方法(Method) 和 语句(Statement) 组成。
1. 最简单的 C# 程序
cs
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
结构说明
| 代码 | 说明 |
|---|---|
| using System; | 引入 System 命名空间 |
| class Program | 定义一个类 |
| static void Main() | 主方法,程序入口 |
| Console.WriteLine() | 输出内容到控制台 |
2. 完整程序结构
cs
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("欢迎学习C#");
}
}
}
结构图
cs
命名空间 Namespace
│
├── 类 Class
│ │
│ ├── Main()方法
│ │ │
│ │ ├── 变量
│ │ ├── 语句
│ │ └── 函数调用
│ │
│ └── 其它方法
│
└── 其它类
3. 命名空间(Namespace)
用于组织和管理代码,避免类名冲突。
cs
namespace StudentManage
{
class Student
{
}
}
调用其它命名空间
cs
using StudentManage;
或者
cs
StudentManage.Student stu = new StudentManage.Student();
4. 类(Class)
C# 是面向对象语言,所有代码都放在类中。
cs
class Person
{
public string Name;
public int Age;
}
创建对象:
cs
Person p = new Person();
p.Name = "张三";
p.Age = 20;
5. Main 方法
Main 方法是程序执行的入口。
cs
static void Main(string[] args)
{
Console.WriteLine("程序开始");
}
常见写法
cs
static void Main()
{
}
cs
static int Main(string[] args)
{
return 0;
}
6. 变量定义
cs
string name = "张三";
int age = 18;
double salary = 5000.5;
bool isVip = true;
7. 方法定义
cs
class MathTool
{
public static int Add(int a, int b)
{
return a + b;
}
}
调用:
cs
int result = MathTool.Add(10, 20);
Console.WriteLine(result);
8. 注释
单行注释
cs
// 输出欢迎信息
Console.WriteLine("Hello");
多行注释
/*
这是多行注释
可以写很多内容
*/
XML注释
cs
/// <summary>
/// 求和方法
/// </summary>
public int Add(int a,int b)
{
return a + b;
}
9. 一个完整案例
cs
using System;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
string name = "张三";
int age = 20;
ShowInfo(name, age);
}
static void ShowInfo(string name, int age)
{
Console.WriteLine("姓名:" + name);
Console.WriteLine("年龄:" + age);
}
}
}
运行结果:
cs
姓名:张三
年龄:20
10. C# 程序执行流程
程序启动
↓
进入 Main()
↓
执行代码
↓
调用方法
↓
返回结果
↓
程序结束