随笔 - 303  文章 - 0  评论 - 11  阅读 - 15万

延迟加载

我们创建某一个对象需要很大的消耗,而这个对象在运行过程中又不一定用到,为了避免每次运行都创建该对象,这时候延迟初始化(也叫延迟实例化)就出场了。

延迟初始化出现于.NET 4.0,主要用于提高性能,避免浪费计算,并减少程序内存要求。也可以称为,按需加载。

 

Lazy<T> xx = new Lazy<T>();//xx代表变量名

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace LazyTest
{
    class Student
    {
        public Student()
        {
            this.Name = "DefaultName";
            Console.WriteLine("调用Student的构造函数");
        }
 
        public string Name { get; set; }
    }
}

  

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LazyTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Lazy<Student> student = new Lazy<Student>();
            if (!student.IsValueCreated)
            {
                Console.WriteLine("Student未初始化");
            }
            Console.WriteLine(student.Value.Name);
            if (student.IsValueCreated)
            {
                Console.WriteLine("Student已经初始化");
            }
            Console.ReadKey();
        }
    }
}
复制代码

 

posted on   雪原日暮  阅读(130)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示