C# 基础语法
本章将详细介绍 C# 的基础语法,包括变量、数据类型、运算符、常量等核心概念,为后续学习打下坚实基础。
变量和标识符
变量声明
在 C# 中,变量必须先声明后使用:
csharp
// 基本变量声明语法
数据类型 变量名;
数据类型 变量名 = 初始值;
// 示例
int age; // 声明整数变量
string name = "Alice"; // 声明并初始化字符串变量
double salary = 5000.50; // 声明并初始化双精度浮点数
bool isActive = true; // 声明并初始化布尔变量变量初始化
csharp
// 声明时初始化(推荐)
int count = 0;
string message = "Hello";
// 先声明后赋值
int number;
number = 42;
// 多个变量同时声明
int x, y, z;
int a = 1, b = 2, c = 3;
// 使用 var 关键字(类型推断)
var temperature = 25.5; // 推断为 double
var city = "Beijing"; // 推断为 string
var isReady = false; // 推断为 bool标识符命名规则
csharp
// 有效的标识符
int age;
string firstName;
double _salary;
bool isValid2;
string userName;
// 无效的标识符
// int 2age; // 不能以数字开头
// string first-name; // 不能包含连字符
// bool class; // 不能使用关键字
// double my var; // 不能包含空格命名规则:
- 必须以字母、下划线或 @ 符号开头
- 后续字符可以是字母、数字或下划线
- 区分大小写
- 不能使用 C# 关键字
- 不能包含空格或特殊字符
命名约定:
csharp
// 变量和方法:camelCase(驼峰命名法)
int studentAge;
string firstName;
void calculateTotal();
// 类和属性:PascalCase(帕斯卡命名法)
class StudentInfo;
public string FirstName { get; set; }
// 常量:全大写,下划线分隔
const int MAX_SIZE = 100;
const string DEFAULT_NAME = "Unknown";
// 私有字段:下划线前缀
private int _count;
private string _name;数据类型
值类型 (Value Types)
整数类型
csharp
// 有符号整数
sbyte smallNumber = -128; // 8位,-128 到 127
short mediumNumber = -32768; // 16位,-32,768 到 32,767
int regularNumber = -2147483648; // 32位,-2,147,483,648 到 2,147,483,647
long bigNumber = -9223372036854775808L; // 64位
// 无符号整数
byte positiveSmall = 255; // 8位,0 到 255
ushort positiveMedium = 65535; // 16位,0 到 65,535
uint positiveRegular = 4294967295U; // 32位,0 到 4,294,967,295
ulong positiveBig = 18446744073709551615UL; // 64位
// 使用示例
int score = 95;
long population = 1400000000L;
byte red = 255, green = 128, blue = 0;
Console.WriteLine($"分数: {score}");
Console.WriteLine($"人口: {population:N0}");
Console.WriteLine($"RGB: ({red}, {green}, {blue})");浮点类型
csharp
// 单精度浮点数(32位)
float temperature = 36.5f;
float pi = 3.14159f;
// 双精度浮点数(64位,默认)
double distance = 384400.0;
double e = 2.718281828459045;
// 高精度十进制(128位)
decimal price = 199.99m;
decimal taxRate = 0.08m;
// 精度比较
float f = 0.1f + 0.2f;
double d = 0.1 + 0.2;
decimal m = 0.1m + 0.2m;
Console.WriteLine($"float: {f}"); // 可能不精确
Console.WriteLine($"double: {d}"); // 可能不精确
Console.WriteLine($"decimal: {m}"); // 精确的 0.3字符和布尔类型
csharp
// 字符类型(16位 Unicode)
char letter = 'A';
char digit = '9';
char symbol = '@';
char unicode = '\u4E2D'; // 中文字符 '中'
// 布尔类型
bool isTrue = true;
bool isFalse = false;
bool isValid = (10 > 5); // 表达式结果
// 使用示例
Console.WriteLine($"字符: {letter}");
Console.WriteLine($"Unicode: {unicode}");
Console.WriteLine($"验证结果: {isValid}");引用类型 (Reference Types)
字符串类型
csharp
// 字符串声明和初始化
string name = "Alice";
string empty = "";
string nullString = null;
string multiline = @"这是一个
多行字符串";
// 字符串操作
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
string formatted = $"姓名: {firstName} {lastName}";
Console.WriteLine(fullName);
Console.WriteLine(formatted);
Console.WriteLine($"长度: {fullName.Length}");对象类型
csharp
// object 是所有类型的基类
object obj1 = 42;
object obj2 = "Hello";
object obj3 = true;
// 装箱和拆箱
int number = 100;
object boxed = number; // 装箱
int unboxed = (int)boxed; // 拆箱
Console.WriteLine($"装箱: {boxed}");
Console.WriteLine($"拆箱: {unboxed}");可空类型 (Nullable Types)
csharp
// 可空值类型
int? nullableInt = null;
double? nullableDouble = 3.14;
bool? nullableBool = null;
// 检查是否有值
if (nullableInt.HasValue)
{
Console.WriteLine($"值: {nullableInt.Value}");
}
else
{
Console.WriteLine("没有值");
}
// 空合并操作符
int result = nullableInt ?? 0; // 如果为 null 则使用 0
Console.WriteLine($"结果: {result}");
// 可空引用类型(C# 8.0+)
string? nullableString = null;
string nonNullableString = "Hello";类型转换
隐式转换
csharp
// 安全的隐式转换(不会丢失数据)
int intValue = 100;
long longValue = intValue; // int → long
double doubleValue = intValue; // int → double
float floatValue = intValue; // int → float
Console.WriteLine($"int: {intValue}");
Console.WriteLine($"long: {longValue}");
Console.WriteLine($"double: {doubleValue}");显式转换
csharp
// 可能丢失数据的显式转换
double pi = 3.14159;
int intPi = (int)pi; // 截断小数部分
float floatPi = (float)pi; // 可能丢失精度
long bigNumber = 1000000000L;
int smallNumber = (int)bigNumber; // 可能溢出
Console.WriteLine($"原值: {pi}");
Console.WriteLine($"转换后: {intPi}");类型转换方法
csharp
// Convert 类方法
string numberString = "123";
int converted = Convert.ToInt32(numberString);
double convertedDouble = Convert.ToDouble(numberString);
bool convertedBool = Convert.ToBoolean("true");
// Parse 方法
int parsed = int.Parse("456");
double parsedDouble = double.Parse("3.14");
DateTime parsedDate = DateTime.Parse("2023-12-25");
// TryParse 方法(安全转换)
string input = "789";
if (int.TryParse(input, out int result))
{
Console.WriteLine($"转换成功: {result}");
}
else
{
Console.WriteLine("转换失败");
}
// ToString 方法
int number = 42;
string numberAsString = number.ToString();
string formattedNumber = number.ToString("D5"); // 补零到5位
Console.WriteLine($"字符串: {numberAsString}");
Console.WriteLine($"格式化: {formattedNumber}");运算符
算术运算符
csharp
int a = 10, b = 3;
// 基本算术运算
int addition = a + b; // 加法: 13
int subtraction = a - b; // 减法: 7
int multiplication = a * b; // 乘法: 30
int division = a / b; // 整数除法: 3
int remainder = a % b; // 取余: 1
// 浮点除法
double floatDivision = (double)a / b; // 3.333...
Console.WriteLine($"加法: {a} + {b} = {addition}");
Console.WriteLine($"减法: {a} - {b} = {subtraction}");
Console.WriteLine($"乘法: {a} * {b} = {multiplication}");
Console.WriteLine($"除法: {a} / {b} = {division}");
Console.WriteLine($"取余: {a} % {b} = {remainder}");
Console.WriteLine($"浮点除法: {a} / {b} = {floatDivision:F3}");赋值运算符
csharp
int x = 10;
// 基本赋值
x = 20;
// 复合赋值运算符
x += 5; // x = x + 5; 结果: 25
x -= 3; // x = x - 3; 结果: 22
x *= 2; // x = x * 2; 结果: 44
x /= 4; // x = x / 4; 结果: 11
x %= 3; // x = x % 3; 结果: 2
Console.WriteLine($"最终结果: {x}");
// 字符串复合赋值
string message = "Hello";
message += " World"; // 结果: "Hello World"
message += "!"; // 结果: "Hello World!"
Console.WriteLine(message);比较运算符
csharp
int num1 = 10, num2 = 20;
// 比较运算符
bool equal = (num1 == num2); // 等于: false
bool notEqual = (num1 != num2); // 不等于: true
bool greater = (num1 > num2); // 大于: false
bool less = (num1 < num2); // 小于: true
bool greaterEqual = (num1 >= num2); // 大于等于: false
bool lessEqual = (num1 <= num2); // 小于等于: true
Console.WriteLine($"{num1} == {num2}: {equal}");
Console.WriteLine($"{num1} != {num2}: {notEqual}");
Console.WriteLine($"{num1} > {num2}: {greater}");
Console.WriteLine($"{num1} < {num2}: {less}");
// 字符串比较
string str1 = "apple";
string str2 = "banana";
bool stringEqual = (str1 == str2);
bool stringLess = string.Compare(str1, str2) < 0;
Console.WriteLine($"'{str1}' == '{str2}': {stringEqual}");
Console.WriteLine($"'{str1}' < '{str2}': {stringLess}");逻辑运算符
csharp
bool condition1 = true;
bool condition2 = false;
// 逻辑运算符
bool andResult = condition1 && condition2; // 逻辑与: false
bool orResult = condition1 || condition2; // 逻辑或: true
bool notResult = !condition1; // 逻辑非: false
Console.WriteLine($"true && false = {andResult}");
Console.WriteLine($"true || false = {orResult}");
Console.WriteLine($"!true = {notResult}");
// 短路求值
int a = 5, b = 0;
bool safeCheck = (b != 0) && (a / b > 2); // 短路,不会执行除法
Console.WriteLine($"安全检查: {safeCheck}");
// 复杂逻辑表达式
int age = 25;
bool hasLicense = true;
bool canDrive = (age >= 18) && hasLicense;
Console.WriteLine($"可以开车: {canDrive}");递增和递减运算符
csharp
int counter = 5;
// 前置递增/递减
int preIncrement = ++counter; // 先递增,再使用: counter=6, preIncrement=6
int preDecrement = --counter; // 先递减,再使用: counter=5, preDecrement=5
Console.WriteLine($"前置递增后: counter={counter}, result={preIncrement}");
counter = 5; // 重置
// 后置递增/递减
int postIncrement = counter++; // 先使用,再递增: postIncrement=5, counter=6
int postDecrement = counter--; // 先使用,再递减: postDecrement=6, counter=5
Console.WriteLine($"后置递增后: counter={counter}, result={postIncrement}");
// 在循环中的应用
for (int i = 0; i < 5; i++)
{
Console.Write($"{i} ");
}
Console.WriteLine();条件运算符(三元运算符)
csharp
// 基本语法: condition ? value_if_true : value_if_false
int a = 10, b = 20;
int max = (a > b) ? a : b;
Console.WriteLine($"最大值: {max}");
// 字符串条件
string status = (max > 15) ? "高" : "低";
Console.WriteLine($"状态: {status}");
// 嵌套条件运算符
int score = 85;
string grade = (score >= 90) ? "A" :
(score >= 80) ? "B" :
(score >= 70) ? "C" :
(score >= 60) ? "D" : "F";
Console.WriteLine($"成绩: {grade}");
// 空合并运算符
string name = null;
string displayName = name ?? "匿名用户";
Console.WriteLine($"显示名称: {displayName}");
// 空条件运算符(C# 6.0+)
string text = null;
int? length = text?.Length; // 如果 text 为 null,返回 null
Console.WriteLine($"长度: {length ?? 0}");常量和字面量
常量声明
csharp
// 编译时常量
const int MAX_STUDENTS = 30;
const double PI = 3.14159;
const string COMPANY_NAME = "Microsoft";
const bool DEBUG_MODE = true;
// 只读字段(运行时常量)
static readonly DateTime StartTime = DateTime.Now;
static readonly string ConfigPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
// 使用常量
int classSize = MAX_STUDENTS;
double circumference = 2 * PI * 5; // 半径为5的圆周长
Console.WriteLine($"最大学生数: {MAX_STUDENTS}");
Console.WriteLine($"圆周长: {circumference}");
Console.WriteLine($"公司名称: {COMPANY_NAME}");字面量
csharp
// 整数字面量
int decimal = 42; // 十进制
int hexadecimal = 0x2A; // 十六进制
int binary = 0b101010; // 二进制(C# 7.0+)
int withSeparator = 1_000_000; // 数字分隔符(C# 7.0+)
// 浮点字面量
double d1 = 3.14;
double d2 = 3.14e2; // 科学记数法: 314
float f = 3.14f; // float 后缀
decimal m = 3.14m; // decimal 后缀
// 字符字面量
char letter = 'A';
char escape = '\n'; // 转义字符
char unicode = '\u0041'; // Unicode: 'A'
// 字符串字面量
string regular = "Hello World";
string verbatim = @"C:\Users\Name\Documents"; // 逐字字符串
string interpolated = $"结果是 {decimal}"; // 字符串插值
string raw = """
这是一个
原始字符串字面量
"""; // 原始字符串(C# 11+)
Console.WriteLine($"十进制: {decimal}");
Console.WriteLine($"十六进制: {hexadecimal}");
Console.WriteLine($"二进制: {binary}");
Console.WriteLine($"带分隔符: {withSeparator:N0}");注释
单行注释
csharp
// 这是单行注释
int age = 25; // 变量声明注释
// TODO: 实现用户验证功能
// FIXME: 修复除零错误
// NOTE: 这个算法需要优化多行注释
csharp
/*
* 这是多行注释
* 可以跨越多行
* 通常用于较长的说明
*/
int CalculateArea(int width, int height)
{
/*
* 计算矩形面积
* 参数验证在调用方进行
*/
return width * height;
}XML 文档注释
csharp
/// <summary>
/// 计算两个整数的和
/// </summary>
/// <param name="a">第一个整数</param>
/// <param name="b">第二个整数</param>
/// <returns>两个整数的和</returns>
/// <example>
/// <code>
/// int result = Add(5, 3); // 返回 8
/// </code>
/// </example>
public int Add(int a, int b)
{
return a + b;
}
/// <summary>
/// 学生信息类
/// </summary>
/// <remarks>
/// 这个类用于存储学生的基本信息
/// 包括姓名、年龄和成绩
/// </remarks>
public class Student
{
/// <summary>
/// 获取或设置学生姓名
/// </summary>
/// <value>学生的姓名</value>
public string Name { get; set; }
/// <summary>
/// 获取或设置学生年龄
/// </summary>
/// <value>学生的年龄,必须大于0</value>
public int Age { get; set; }
}实践示例
示例 1:基本计算器
csharp
using System;
class BasicCalculator
{
static void Main()
{
Console.WriteLine("=== 基本计算器 ===");
// 获取用户输入
Console.Write("请输入第一个数字: ");
double num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("请输入运算符 (+, -, *, /, %): ");
char operation = Console.ReadLine()[0];
Console.Write("请输入第二个数字: ");
double num2 = Convert.ToDouble(Console.ReadLine());
// 执行计算
double result = 0;
bool validOperation = true;
switch (operation)
{
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0)
result = num1 / num2;
else
{
Console.WriteLine("错误: 除数不能为零!");
validOperation = false;
}
break;
case '%':
if (num2 != 0)
result = num1 % num2;
else
{
Console.WriteLine("错误: 除数不能为零!");
validOperation = false;
}
break;
default:
Console.WriteLine("错误: 无效的运算符!");
validOperation = false;
break;
}
// 显示结果
if (validOperation)
{
Console.WriteLine($"结果: {num1} {operation} {num2} = {result}");
}
}
}示例 2:数据类型演示
csharp
using System;
class DataTypeDemo
{
static void Main()
{
Console.WriteLine("=== C# 数据类型演示 ===\n");
// 整数类型
Console.WriteLine("整数类型:");
byte byteValue = 255;
short shortValue = 32767;
int intValue = 2147483647;
long longValue = 9223372036854775807L;
Console.WriteLine($"byte: {byteValue} (范围: 0 到 {byte.MaxValue})");
Console.WriteLine($"short: {shortValue} (范围: {short.MinValue} 到 {short.MaxValue})");
Console.WriteLine($"int: {intValue} (范围: {int.MinValue} 到 {int.MaxValue})");
Console.WriteLine($"long: {longValue} (范围: {long.MinValue} 到 {long.MaxValue})");
// 浮点类型
Console.WriteLine("\n浮点类型:");
float floatValue = 3.14159f;
double doubleValue = 3.141592653589793;
decimal decimalValue = 3.141592653589793238462643383279m;
Console.WriteLine($"float: {floatValue} (精度: ~7位)");
Console.WriteLine($"double: {doubleValue} (精度: ~15-17位)");
Console.WriteLine($"decimal: {decimalValue} (精度: ~28-29位)");
// 字符和布尔类型
Console.WriteLine("\n其他类型:");
char charValue = 'A';
bool boolValue = true;
string stringValue = "Hello, C#!";
Console.WriteLine($"char: '{charValue}' (Unicode: {(int)charValue})");
Console.WriteLine($"bool: {boolValue}");
Console.WriteLine($"string: \"{stringValue}\" (长度: {stringValue.Length})");
// 可空类型
Console.WriteLine("\n可空类型:");
int? nullableInt = null;
double? nullableDouble = 3.14;
Console.WriteLine($"int?: {nullableInt ?? -1} (HasValue: {nullableInt.HasValue})");
Console.WriteLine($"double?: {nullableDouble} (HasValue: {nullableDouble.HasValue})");
// 类型转换
Console.WriteLine("\n类型转换:");
int intNum = 42;
double doubleNum = intNum; // 隐式转换
int backToInt = (int)doubleNum; // 显式转换
string numString = intNum.ToString();
Console.WriteLine($"int → double: {intNum} → {doubleNum}");
Console.WriteLine($"double → int: {doubleNum} → {backToInt}");
Console.WriteLine($"int → string: {intNum} → \"{numString}\"");
}
}示例 3:运算符综合应用
csharp
using System;
class OperatorDemo
{
static void Main()
{
Console.WriteLine("=== 运算符演示 ===\n");
// 算术运算符
Console.WriteLine("算术运算符:");
int a = 15, b = 4;
Console.WriteLine($"a = {a}, b = {b}");
Console.WriteLine($"a + b = {a + b}");
Console.WriteLine($"a - b = {a - b}");
Console.WriteLine($"a * b = {a * b}");
Console.WriteLine($"a / b = {a / b} (整数除法)");
Console.WriteLine($"a / (double)b = {a / (double)b:F2} (浮点除法)");
Console.WriteLine($"a % b = {a % b} (取余)");
// 比较运算符
Console.WriteLine("\n比较运算符:");
Console.WriteLine($"a == b: {a == b}");
Console.WriteLine($"a != b: {a != b}");
Console.WriteLine($"a > b: {a > b}");
Console.WriteLine($"a < b: {a < b}");
Console.WriteLine($"a >= b: {a >= b}");
Console.WriteLine($"a <= b: {a <= b}");
// 逻辑运算符
Console.WriteLine("\n逻辑运算符:");
bool x = true, y = false;
Console.WriteLine($"x = {x}, y = {y}");
Console.WriteLine($"x && y: {x && y}");
Console.WriteLine($"x || y: {x || y}");
Console.WriteLine($"!x: {!x}");
Console.WriteLine($"!y: {!y}");
// 条件运算符
Console.WriteLine("\n条件运算符:");
int max = (a > b) ? a : b;
string result = (a > b) ? "a 更大" : "b 更大或相等";
Console.WriteLine($"最大值: {max}");
Console.WriteLine($"比较结果: {result}");
// 递增递减运算符
Console.WriteLine("\n递增递减运算符:");
int counter = 5;
Console.WriteLine($"初始值: {counter}");
Console.WriteLine($"counter++: {counter++} (使用后递增)");
Console.WriteLine($"当前值: {counter}");
Console.WriteLine($"++counter: {++counter} (递增后使用)");
Console.WriteLine($"当前值: {counter}");
// 复合赋值运算符
Console.WriteLine("\n复合赋值运算符:");
int value = 10;
Console.WriteLine($"初始值: {value}");
value += 5;
Console.WriteLine($"value += 5: {value}");
value *= 2;
Console.WriteLine($"value *= 2: {value}");
value /= 3;
Console.WriteLine($"value /= 3: {value}");
value %= 7;
Console.WriteLine($"value %= 7: {value}");
}
}本章小结
本章详细介绍了 C# 的基础语法:
关键要点:
- 变量声明:类型 变量名 = 初始值
- 数据类型:值类型和引用类型
- 类型转换:隐式转换和显式转换
- 运算符:算术、比较、逻辑、赋值等
- 常量:const 和 readonly 的区别
- 注释:单行、多行和 XML 文档注释
重要概念:
- 强类型语言,变量必须声明类型
- 值类型存储在栈中,引用类型存储在堆中
- 可空类型允许值类型存储 null
- 运算符优先级影响表达式计算顺序
- 类型安全防止运行时错误
最佳实践:
- 使用有意义的变量名
- 遵循命名约定
- 适当使用 var 关键字
- 注意类型转换的安全性
- 添加必要的注释
在下一章中,我们将学习 C# 的控制结构,包括条件语句和循环语句。