C# 是静态类型语言——变量的类型在编译时就已知。你可以使用显式类型声明变量,或者使用 var 进行类型推断(编译器从值推断类型),但无论哪种方式,类型都是固定的。
声明变量
count = ;
name = ;
price = ;
active = ;
age = ;
message = ;
items = List<>();
var 从初始化器推断类型——var age = 30 完全等同于 int age = 30。关键是,var 仍然是静态类型的:类型在编译时固定(你以后不能将字符串分配给 age);它只是被推断出来,而不是动态的。
var x = 5;
x = "hi"; // ❌ compile error — x is an int, can't become a string
var y; // ❌ error — var needs an initializer to infer from
var user = new UserService(); // ✅ type is obvious from the right side — var is clean
var count = users.Count;
int total = CalculateComplexValue(); // explicit when the type isn't obvious aids readability
当类型从右侧明显时使用 var(减少冗余,尤其是对于长泛型类型);当它有助于清晰性时使用显式类型。
const double Pi = 3.14159; // compile-time constant (can't change)
readonly int id; // set once (in constructor), then immutable
int a = 1, b = 2; // multiple of the same type
nint nativeInt; // platform-sized integer
int, long, short, byte integers
float, double, decimal floating point (decimal for money — exact)
bool, char, string boolean, character, text
object the base of all types
理解变量声明和 var 是日常 C# 基础知识。
关键概念是 var 是类型推断,不是动态类型 —— 这是一个常见的误解。
使用 var 时,编译器从初始化器推断类型,但类型仍然在编译时固定(你获得静态类型的所有好处——类型检查、IntelliSense、性能),只是不用显式写出类型名。
this makes var a convenience for readability (especially with verbose generic types like Dictionary<string, List<int>>) rather than a loosening of the type system.
知道何时使用 var(当类型从右侧明显时,减少冗余)与何时使用显式类型(当它有助于清晰性时),以及内置类型(特别是 用于金钱的 decimal —— 精确的十进制算术,不同于 double)、常量(const、readonly),是编写 C# 的日常知识。
理解 C# 始终是静态类型的(无论你写出类型还是使用 var),以及围绕变量声明的习语,是阅读和编写干净、正确 C# 代码的基础,而 var 不是动态的这一点是频繁的澄清,反映了对语言的正确理解。