C# 变量

声明、初始化、`var`、可空类型、以及 `const` 与 `readonly`。

Beginner
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 hello
C#
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
True

const 与 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
ModifierWhen setAllowed 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
10

C# forbids redeclaring a name in the same scope (unlike JavaScript's var). Inner blocks may shadow, though the compiler warns.

Friends & Partners