在C#中,可以使用以下几种方式定义和初始化变量:
- 在声明变量时直接初始化:
int myNumber = 10; string myName = "John Doe"; bool isAvailable = true;
- 声明变量后,使用赋值语句进行初始化:
int myNumber; myNumber = 10; string myName; myName = "John Doe"; bool isAvailable; isAvailable = true;
- 使用匿名类型进行初始化:
var myNumber = 10; var myName = "John Doe"; var isAvailable = true;
- 使用对象初始化器进行初始化(仅适用于类实例):
Person person = new Person { Name = "John Doe", Age = 30, IsAvailable = true };
- 使用集合初始化器进行初始化(仅适用于集合类型,如List、Dictionary等):
Listnumbers = new List { 1, 2, 3, 4, 5 }; Dictionary availability = new Dictionary { { "John Doe", true }, { "Jane Smith", false } };