变量与常量 #

一、变量概述 #

变量是存储数据的容器,它有一个名称(变量名)和一个数据类型。变量的值在程序运行过程中可以改变。

1.1 变量声明 #

csharp
int age;
string name;
double price;

1.2 变量初始化 #

csharp
int age = 25;
string name = "张三";
double price = 99.99;

1.3 声明多个变量 #

csharp
int a, b, c;
int x = 1, y = 2, z = 3;

二、变量类型 #

2.1 局部变量 #

在方法内部声明的变量:

csharp
void MyMethod()
{
    int count = 0;
    string message = "Hello";
}

2.2 字段(成员变量) #

在类中声明的变量:

csharp
public class Person
{
    private string name;
    public int age;
    protected DateTime birthDate;
}

2.3 静态变量 #

使用static关键字声明:

csharp
public class Counter
{
    private static int totalCount = 0;
}

2.4 只读变量 #

使用readonly关键字声明,只能在构造函数中赋值:

csharp
public class Configuration
{
    private readonly string connectionString;
    
    public Configuration(string connString)
    {
        connectionString = connString;
    }
}

三、var关键字 #

3.1 隐式类型局部变量 #

使用var关键字,编译器自动推断类型:

csharp
var number = 42;
var text = "Hello";
var list = new List<int>();
var dict = new Dictionary<string, int>();

3.2 var使用规则 #

必须初始化:

csharp
var number;

类型确定后不能改变:

csharp
var value = 42;
value = "Hello";

适用场景:

csharp
var numbers = new List<int> { 1, 2, 3, 4, 5 };
var result = from n in numbers where n > 2 select n;
var person = new { Name = "张三", Age = 25 };

3.3 var vs 显式类型 #

场景 推荐方式
基本类型 显式类型
复杂泛型 var
匿名类型 必须用var
LINQ查询 var
csharp
int age = 25;
var users = new Dictionary<string, List<User>>();
var query = from u in users select u;

四、常量 #

4.1 const常量 #

const常量在编译时确定值,声明时必须初始化:

csharp
public const double PI = 3.14159;
public const int MaxRetryCount = 3;
public const string AppName = "MyApp";

特点:

  • 编译时常量
  • 声明时必须赋值
  • 不能修改
  • 默认为静态

4.2 const使用示例 #

csharp
public class MathConstants
{
    public const double PI = 3.14159265359;
    public const double E = 2.71828182846;
    public const double GoldenRatio = 1.61803398875;
}

double area = MathConstants.PI * radius * radius;

4.3 readonly vs const #

特性 const readonly
赋值时机 编译时 运行时
赋值位置 声明时 声明时或构造函数
类型限制 基本类型、字符串、null 任意类型
静态性 隐式静态 可静态可实例
csharp
public class Settings
{
    public const string Version = "1.0.0";
    public readonly DateTime CreatedAt;
    
    public Settings()
    {
        CreatedAt = DateTime.Now;
    }
}

五、命名规则 #

5.1 变量命名规范 #

基本规则:

  • 以字母或下划线开头
  • 只包含字母、数字、下划线
  • 区分大小写
  • 不能使用关键字

命名约定:

类型 约定 示例
局部变量 camelCase totalCount
私有字段 _camelCase _userName
公有字段 PascalCase UserName
常量 PascalCase或UPPER_CASE MaxSize

5.2 命名最佳实践 #

有意义的名称:

csharp
int d;
int daysSinceModification;

避免缩写:

csharp
int usrCnt;
int userCount;

布尔变量使用is/has前缀:

csharp
bool isValid = true;
bool hasPermission = false;
bool canEdit = true;

集合使用复数:

csharp
var users = new List<User>();
var products = new List<Product>();

六、变量的作用域 #

6.1 块级作用域 #

csharp
if (condition)
{
    int x = 10;
}

6.2 方法作用域 #

csharp
void MyMethod()
{
    int x = 10;
    if (true)
    {
        int y = 20;
        Console.WriteLine(x);
        Console.WriteLine(y);
    }
}

6.3 类作用域 #

csharp
public class MyClass
{
    private int _count = 0;
    
    public void Increment()
    {
        _count++;
    }
    
    public int GetCount()
    {
        return _count;
    }
}

七、可空类型 #

7.1 可空值类型 #

csharp
int? nullableInt = null;
double? nullableDouble = 10.5;
bool? nullableBool = null;

7.2 可空引用类型(C# 8+) #

启用可空引用类型:

xml
<Nullable>enable</Nullable>
csharp
string? nullableString = null;
string nonNullableString = "Hello";

7.3 空值检查 #

csharp
string? name = GetName();

if (name != null)
{
    Console.WriteLine(name.Length);
}

int length = name?.Length ?? 0;

八、默认值 #

8.1 各类型的默认值 #

类型 默认值
int, long, short等 0
float, double 0.0
decimal 0.0m
bool false
char ‘\0’
引用类型 null
可空类型 null

8.2 使用default关键字 #

csharp
int number = default;
string text = default;
List<int> list = default;

8.3 使用default表达式 #

csharp
int number = default(int);
string text = default(string);

九、实战示例 #

9.1 配置类示例 #

csharp
public class AppConfig
{
    public const string AppName = "MyApplication";
    public const string Version = "1.0.0";
    
    private readonly string _connectionString;
    private readonly DateTime _startTime;
    
    public int MaxRetryCount { get; set; } = 3;
    public bool EnableLogging { get; set; } = true;
    
    public AppConfig(string connectionString)
    {
        _connectionString = connectionString;
        _startTime = DateTime.Now;
    }
}

9.2 计算器示例 #

csharp
public class Calculator
{
    private double _result = 0;
    
    public void Add(double value)
    {
        _result += value;
    }
    
    public void Subtract(double value)
    {
        _result -= value;
    }
    
    public void Multiply(double value)
    {
        _result *= value;
    }
    
    public void Divide(double value)
    {
        if (value != 0)
        {
            _result /= value;
        }
    }
    
    public void Clear()
    {
        _result = 0;
    }
    
    public double GetResult()
    {
        return _result;
    }
}

十、最佳实践 #

10.1 变量使用建议 #

  1. 就近声明:在使用的地方声明变量
  2. 初始化:声明时尽量初始化
  3. 最小作用域:限制变量的作用域
  4. 有意义的名称:使用描述性名称
csharp
void ProcessOrder(Order order)
{
    var orderItems = order.Items;
    var totalPrice = orderItems.Sum(i => i.Price * i.Quantity);
    var discount = CalculateDiscount(totalPrice);
    var finalPrice = totalPrice - discount;
    
    Console.WriteLine($"订单总价:{finalPrice}");
}

10.2 常量使用建议 #

  1. 魔法数字:用常量替代魔法数字
  2. 配置值:不变的配置值使用常量
  3. 业务规则:业务规则常量集中管理
csharp
public static class BusinessRules
{
    public const int MaxLoginAttempts = 5;
    public const int PasswordMinLength = 8;
    public const int SessionTimeoutMinutes = 30;
    public const decimal TaxRate = 0.13m;
}

十一、总结 #

变量与常量要点:

要点 说明
变量声明 类型 + 变量名
变量初始化 声明时赋值
var关键字 隐式类型推断
const常量 编译时常量
readonly 运行时常量
命名规范 camelCase/PascalCase

下一步,让我们学习C#的基本数据类型!

最后更新:2026-03-26