C# 变量
声明、初始化、`var`、可空类型、以及 `const` 与 `readonly`。
Key Points局部变量必须先赋值才能用;字段会有默认值。
声明与初始化
C#
int a = 1;
int b, c; // 声明多个
b = 2;
c = 3;
var d = 4; // 类型推断
var s = "hello";
Console.WriteLine($"{a} {b} {c} {d} {s}");Output
1 2 3 4 helloC#
int x;
// Console.WriteLine(x); // 编译错误:使用了未赋值的局部变量
x = 10;
Console.WriteLine(x);Output
10可空类型
C#
int? n = null;
Console.WriteLine(n.HasValue);
Console.WriteLine(n.GetValueOrDefault());
Console.WriteLine(n ?? -1);
n = 5;
Console.WriteLine(n.Value * 2);
// 值类型的 ? 是 Nullable<T> 的语法糖
Nullable<int> same = 5;
Console.WriteLine(same == n);Output
False
0
-1
10
Trueconst 与 readonly
C#
class Config
{
public const double Pi = 3.14159; // 编译期常量
public static readonly DateTime Start; // 运行期初始化,之后只读
static Config()
{
Start = DateTime.Now;
}
}
Console.WriteLine(Config.Pi);
Console.WriteLine(Config.Start.Year > 2000);Output
3.14159
True| Modifier | When set | Allowed types |
|---|---|---|
const | 编译期 | 基本类型 + string |
readonly | 运行期(构造时) | 任意 |
static readonly | 静态构造时 | 任意 |
const values are inlined into callers. If assembly A uses a const from B and B changes it, A keeps the old value unless rebuilt. Use static readonly across assemblies.变量命名与作用域
C#
int outer = 1;
{
int inner = 2;
Console.WriteLine($"{outer} {inner}");
}
// Console.WriteLine(inner); // 编译错误:超出作用域
for (int i = 0; i < 2; i++)
{
int temp = i * 10;
Console.WriteLine(temp);
}Output
1 2
0
10C# forbids redeclaring a name in the same scope (unlike JavaScript's var). Inner blocks may shadow, though the compiler warns.
声明与初始化
C#
int a = 1;
int b, c; // 声明多个
b = 2;
c = 3;
var d = 4; // 类型推断
var s = "hello";
Console.WriteLine($"{a} {b} {c} {d} {s}");Output
1 2 3 4 helloC#
int x;
// Console.WriteLine(x); // 编译错误:使用了未赋值的局部变量
x = 10;
Console.WriteLine(x);Output
10可空类型
C#
int? n = null;
Console.WriteLine(n.HasValue);
Console.WriteLine(n.GetValueOrDefault());
Console.WriteLine(n ?? -1);
n = 5;
Console.WriteLine(n.Value * 2);
// 值类型的 ? 是 Nullable<T> 的语法糖
Nullable<int> same = 5;
Console.WriteLine(same == n);Output
False
0
-1
10
Trueconst 与 readonly
C#
class Config
{
public const double Pi = 3.14159; // 编译期常量
public static readonly DateTime Start; // 运行期初始化,之后只读
static Config()
{
Start = DateTime.Now;
}
}
Console.WriteLine(Config.Pi);
Console.WriteLine(Config.Start.Year > 2000);Output
3.14159
True| 修饰符 | 何时确定 | 可用类型 |
|---|---|---|
const | 编译期 | 基本类型 + string |
readonly | 运行期(构造时) | 任意 |
static readonly | 静态构造时 | 任意 |
const 的值会被内联到调用方。如果 A 程序集引用了 B 里的 const,改了 B 的常量值后,A 不重新编译就还是旧值。跨程序集的常量用 static readonly。变量命名与作用域
C#
int outer = 1;
{
int inner = 2;
Console.WriteLine($"{outer} {inner}");
}
// Console.WriteLine(inner); // 编译错误:超出作用域
for (int i = 0; i < 2; i++)
{
int temp = i * 10;
Console.WriteLine(temp);
}Output
1 2
0
10C# 不允许在同一个作用域里重复声明同名变量(这点和 JavaScript 的 var 不同)。内层块可以遮蔽外层,但会有编译警告。