跳到主要内容

C# 基础语法

本章将介绍 C# 的基础语法,包括语法结构、注释、命名规范等。

第一个 C# 程序

using System;

namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
}

代码解析

部分说明
using System;引入命名空间,类似于其他语言的 import
namespace HelloWorld命名空间,用于组织代码
class Program定义一个类
static void Main(string[] args)程序入口方法
Console.WriteLine()输出到控制台

简化写法(C# 9+)

// 顶级语句(Top-level statements),无需显式 Main 方法
Console.WriteLine("Hello, World!");

注释

单行注释

// 这是单行注释
int age = 25; // 行尾注释

多行注释

/*
* 这是多行注释
* 可以跨越多行
*/

文档注释

/// <summary>
/// 计算两个数的和
/// </summary>
/// <param name="a">第一个数</param>
/// <param name="b">第二个数</param>
/// <returns>返回两数之和</returns>
int Add(int a, int b) => a + b;

标识符命名规则

命名规范

// 正确的命名
string userName; // 驼峰命名法(变量、方法)
int MaxValue; // 帕斯卡命名法(类、属性)
const int MaxCount; // 帕斯卡命名法(常量)

// 不推荐的命名
string n; // 含义不明
string _name; // 以下划线开头(仅限私有字段)
string USER_NAME; // 全大写(常量除外)

命名约定

类型命名方式示例
类、接口帕斯卡class StudentService
方法帕斯卡void GetUserById()
属性帕斯卡public string Name { get; set; }
字段下划线+驼峰private int _age
参数驼峰void SetName(string userName)
常量帕斯卡const int MaxRetryCount = 3
枚举帕斯卡enum Color { Red, Green }

关键字

C# 有保留的关键字,不能用作标识符:

// 常见关键字
abstract, as, base, bool, break, byte, case, catch, char, checked,
class, const, continue, decimal, default, delegate, do, double, else,
enum, event, explicit, extern, false, finally, fixed, float, for,
foreach, goto, if, implicit, in, int, interface, internal, is, lock,
long, namespace, new, null, object, operator, out, override, params,
private, protected, public, readonly, ref, return, sbyte, sealed,
short, sizeof, stackalloc, static, string, struct, switch, this,
throw, true, try, typeof, uint, ulong, unchecked, unsafe, ushort,
using, virtual, void, volatile, while

上下文关键字

某些关键字只在特定上下文中有关键字意义,可以用作标识符:

// 这些可以作为标识符使用
var add = 5; // var 是上下文关键字
dynamic name = "Tom";

代码块和语句

语句结束

// 每条语句以分号结束
int a = 1;
int b = 2;
int c = a + b;

代码块

// 使用大括号组织代码块
if (a > b)
{
Console.WriteLine("a 大于 b");
}
else
{
Console.WriteLine("a 小于等于 b");
}

常用转义字符

// 常见转义字符
Console.WriteLine("第一行\n第二行"); // \n 换行
Console.WriteLine("Tab\t效果"); // \t 制表符
Console.WriteLine("双引号\""); // \" 转义引号
Console.WriteLine("反斜杠\\"); // \\ 转义反斜杠

// @ 逐字字符串(不转义)
string path = @"C:\Users\John\Documents";
string sql = @"SELECT *
FROM Users
WHERE Id = 1";

命名空间

定义命名空间

namespace MyCompany.Project.Services
{
class UserService
{
// ...
}
}

嵌套命名空间

namespace Outer
{
namespace Inner
{
class MyClass { }
}
}

// 简写形式
namespace Outer.Inner
{
class MyClass { }
}

using 指令

using System;                    // 引入系统命名空间
using System.Collections.Generic; // 引入集合命名空间
using Alias = System.Console; // 给命名空间起别名

// 在代码中使用
Console.WriteLine("Hello");
// 或使用别名
Alias.WriteLine("Hello");

全局 using(C# 10+)

// Program.cs
global using System;
global using System.Collections.Generic;
global using static System.Console;

// 这样在项目中任何地方都可以直接使用这些命名空间的内容

控制台输入输出

输出

Console.Write("不换行输出");
Console.WriteLine("换行输出");

// 格式化输出
string name = "张三";
int age = 25;
Console.WriteLine("姓名: {0}, 年龄: {1}", name, age);

// 字符串插值(C# 6+)
Console.WriteLine($"姓名: {name}, 年龄: {age}");

输入

// 读取一行
string input = Console.ReadLine();

// 读取单个字符
int key = Console.Read();

// 读取并解析
int number = int.Parse(Console.ReadLine());
// 或
int number = Convert.ToInt32(Console.ReadLine());

// 安全转换
if (int.TryParse(Console.ReadLine(), out int result))
{
Console.WriteLine($"转换成功: {result}");
}

程序结构示例

using System;

namespace MyApp
{
// 主类
class Program
{
// 入口方法
static void Main(string[] args)
{
// 欢迎信息
PrintWelcome();

// 获取输入
Console.Write("请输入您的名字: ");
string name = Console.ReadLine();

// 输出问候
Console.WriteLine($"您好,{name}!");
}

// 自定义方法
static void PrintWelcome()
{
Console.WriteLine("=================================");
Console.WriteLine(" 欢迎使用本程序 ");
Console.WriteLine("=================================");
}
}
}

小结

  1. 基本结构:using → namespace → class → Main 方法
  2. 注释:单行、多行、文档注释
  3. 命名规范:帕斯卡命名、驼峰命名、下划线前缀
  4. 输出输入:Console.WriteLine、Console.ReadLine
  5. 字符串:普通字符串、转义字符、逐字字符串

练习

  1. 创建一个程序,输出自己的姓名和年龄
  2. 使用字符串插值格式化输出个人信息
  3. 创建一个计算器程序,获取用户输入并计算
  4. 了解 C# 10 的全局 using 功能