C#哪些类型需要 手动初始化

注意:如果出现 元素默认是null:必须手动初始化每个元素!

一、会自动初始化的情况

  1. 所有值类型

    • int, float, double, decimal 等数字类型 → 初始化为0

    • bool → 初始化为 false

    • char → 初始化为 '\0' (Unicode 0)

    • DateTime → 初始化为 DateTime.MinValue (0001-01-01)

    • 结构体(struct)→ 所有字段初始化为默认值

    • Enum(枚举)→ 初始化为0对应的枚举值

二、需要手动初始化的情况

  1. 引用类型

    • string → 初始化为 null(不可用,需要手动初始化)

    • 类对象 → 初始化为 null(不可用,需要手动初始化)

    • 数组

    • List

    • 结构体(struct)中含有引用类型=》(需要手动初始化)

三、数组创建 ≠ 元素创建

如果List<T>和T 中的T是"值类型"=》直接new 数组就行。元素会默认创建!

如果T是"引用类型"=》"类"类型,需要元素创建(不管是一维还是二维);

如:string类型,除了new + 也要创建string元素(不然,都为null)!

复制代码
// 1. 集合和数组
    private List<int> _list = new List<int>();      // 否则为null
    private int[] _array = new int[10];             // 否则为null

3.1 一维数组

1.创建数组但不创建元素对象

public class Person

{

public string Name { get; set; }

public int Age { get; set; }

}

// 只创建数组,不创建Person对象

Person\[\] people1 = new Person3; // 3个null元素

Console.WriteLine(people10); // null

Console.WriteLine(people11); // null

Console.WriteLine(people12); // null

// ❌ 错误:NullReferenceException

// people10.Name = "张三";

2.创建数组但不创建元素对象

Person\[\] people2 = new Person3;

// 必须逐个初始化

people20 = new Person { Name = "张三", Age = 25 };

people21 = new Person { Name = "李四", Age = 30 };

people22 = new Person { Name = "王五", Age = 28 };

方式3:声明时直接初始化(推荐)

// 一步完成数组创建和元素初始化

Person\[\] people3 = new Person\[\]

{

new Person { Name = "张三", Age = 25 },

new Person { Name = "李四", Age = 30 },

new Person { Name = "王五", Age = 28 }

};

// 简写(去掉new Person\[\])

Person\[\] people4 =

{

new Person { Name = "张三", Age = 25 },

new Person { Name = "李四", Age = 30 },

new Person { Name = "王五", Age = 28 }

};

4.使用循环批量初始化

// 创建100个元素的数组

Person\[\] people = new Person100;

// 使用循环初始化所有元素

for (int i = 0; i < people.Length; i++)

{

peoplei = new Person

{

Name = $"人员{i + 1}",

Age = Random.Shared.Next(18, 60)

};

}

3.2、二维数组

public class Cell

{

public int Value { get; set; }

}

// 创建2x3的二维数组(所有元素为null)

Cell, grid1 = new Cell2, 3;

// 逐个初始化

grid10, 0 = new Cell { Value = 1 };

grid10, 1 = new Cell { Value = 2 };

// ... 其他元素仍是null

// 声明时直接初始化

Cell, grid2 = new Cell,

{

{ new Cell { Value = 1 }, new Cell { Value = 2 }, new Cell { Value = 3 } },

{ new Cell { Value = 4 }, new Cell { Value = 5 }, new Cell { Value = 6 } }

};

四、

对比总结表

类型 数组 new T[n] List<T> new List<T>(n) List<T> new List<T>()
值类型 int, struct 创建n个元素 全部初始化为默认值 只设置容量 Count=0(空列表) 空列表 Count=0
string (引用类型) 创建n个元素 全部初始化为null 只设置容量 Count=0(空列表) 空列表 Count=0
类类型 class 创建n个元素 全部初始化为null 只设置容量 Count=0(空列表) 空列表 Count=0

记住这个简单规则:

  • 数组new T[n]:创建n个"槽位",值类型填0,引用类型填null

  • List<T>:创建"空盒子",需要你手动往里放东西

五、string\类类型数组, new Tn的时候,如何初始化,才能直接使用,不为null?

5.1

1. string数组的初始化方法

方法1:声明时直接初始化

复制代码
// 创建并立即初始化所有元素
string[] names = { "张三", "李四", "王五" };

// 或者明确指定大小
string[] names2 = new string[3] { "张三", "李四", "王五" };

方法2:初始化空字符串

复制代码
// 创建3个空字符串,不是null!
string[] emptyStrings = new string[3] { string.Empty, string.Empty, string.Empty };

// 简写
string[] emptyStrings2 = { string.Empty, string.Empty, string.Empty };

方法3:使用重复值初始化

复制代码
using System.Linq;

// 创建包含5个空字符串的数组
string[] array = Enumerable.Repeat(string.Empty, 5).ToArray();

// 或者创建5个相同的默认值
string[] defaults = Enumerable.Repeat("默认值", 5).ToArray();
// 结果:{"默认值", "默认值", "默认值", "默认值", "默认值"}

2. 类类型数组的初始化方法

方法1:声明时直接初始化

复制代码
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

// 创建并初始化所有Person对象
Person[] people = 
{
    new Person { Name = "张三", Age = 25 },
    new Person { Name = "李四", Age = 30 },
    new Person { Name = "王五", Age = 28 }
};

// 或者明确指定大小
Person[] people2 = new Person[3]
{
    new Person { Name = "张三", Age = 25 },
    new Person { Name = "李四", Age = 30 },
    new Person { Name = "王五", Age = 28 }
};

方法2:使用循环初始化

复制代码
// 创建10个Person对象数组,全部不为null
Person[] team = new Person[10];

for (int i = 0; i < team.Length; i++)
{
    team[i] = new Person();  // 初始化每个元素
    // 可以直接使用
    team[i].Name = $"成员{i + 1}";
    team[i].Age = 20 + i;
}

// 现在可以直接使用
Console.WriteLine(team[0].Name);  // "成员1"

**六、**string\类类型数组, List Tn的时候,如何初始化,才能直接使用,不为null?

注意:List<T>永远不会自动添加元素!(无论是值类型还是引用类型)

1. T:值类型

// 即使是值类型,也需要手动添加

List<int> numbers = new List<int>();

numbers.Add(1); // 必须添加

numbers.Add(2);

// 或者使用集合初始化器

List<int> numbers2 = new List<int> { 1, 2, 3, 4, 5 };

2. T:引用类型

List<Person> personList = new List<Person>();

// 批量添加

personList.AddRange(Enumerable.Range(1, 100)

.Select(i => new Person { Id = i }));

// 或者使用循环

for (int i = 0; i < 100; i++)

{

personList.Add(new Person { Id = i + 1 });

}

七、C#中二维数组,用List如何替换?

// 二维数组方式

int, array2D = new int3, 4;

// 使用List替换

List<List<int>> list2D = new List<List<int>>();

// 初始化

for (int i = 0; i < 3; i++)

{

list2D.Add(new List<int>());

for (int j = 0; j < 4; j++)

{

list2Di.Add(0); // 初始化值

}

}

// 访问元素

int value = list2D12; // 相当于 array2D1,2

list2D12 = 99;

相关推荐
灯澜忆梦5 小时前
GO_并发编程---定时器
开发语言·后端·golang
-银雾鸢尾-5 小时前
C#中的StringBuilder相关方法
开发语言·c#
-银雾鸢尾-6 小时前
C#中结构体与类的区别;抽象类与接口的区别
开发语言·c#
大模型码小白7 小时前
【Python零基础教程】继承、多态与魔法函数:面向对象编程三大核心特性详解
java·大数据·开发语言·人工智能·python·ai编程
段一凡-华北理工大学9 小时前
向量数据库实战:选型、调优与落地~系列文章12:文本分块策略实战:chunk_size 怎么选?重叠多少?
开发语言·数据库·后端·oracle·rust·工业智能体·高炉智能化
Ljwuhe9 小时前
C++——多态
开发语言·c++
心平气和量大福大10 小时前
C#-WPF-Window主窗体
开发语言·c#·wpf
白露与泡影10 小时前
Arthas 实战指南:从方法耗时定位到 JVM 变量热修改
服务器·jvm·c#
从零开始的代码生活_11 小时前
C++ 继承详解:访问控制、对象模型、菱形继承与设计取舍
开发语言·c++·后端·学习·算法
云小逸11 小时前
【C++ 第七阶段:模板、泛型编程与工程综合详解】
开发语言·c++