自定义延迟加载类
延迟加载类
1 public class LazyLoader<TModel> where TModel:class 2 { 3 TModel _data; 4 Func<TModel> _loadDataFunc = null; 5 bool _loaded = false; 6 public LazyLoader():this(null){ } 7 public LazyLoader(Func<TModel> loadDataFunc) 8 { 9 _loadDataFunc = loadDataFunc; 10 _data = null; 11 _loaded = false; 12 } 13 public TModel QueryData() 14 { 15 if (!_loaded && _loadDataFunc != null) 16 { 17 _data = _loadDataFunc(); 18 } 19 return _data; 20 } 21 public void SetData(TModel value) 22 { 23 _data = value; 24 _loaded = true; 25 } 26 }
使用方法(简单举列)
比如员工菜单 可能你再使用这个员工对象的时候并不需要去加载他的菜单 当你要用的时候再加载 这时候就需要延迟加载了
1 public class Employee 2 { 3 public LazyLoader<IEnumerable<Menu>> _menus; 4 public Employee(Guid employeeId, string employeeNo, string name, string password, string email, string phone, bool enabled, bool isAdministrtor, DateTime registerDate, string remark, string ipLimitation) 5 { 6 EmployeeId = employeeId; 7 EmployeeNo = employeeNo; 8 Name = name; 9 Password = password; 10 Email = email; 11 Phone = phone; 12 Enabled = enabled; 13 IsAdministrator = isAdministrtor; 14 RegisterDate = registerDate; 15 Remark = remark; 16 IpLimitation = ipLimitation; 17 _menus = new LazyLoader<IEnumerable<Menu>>(() => SystemResourceService.QueryMenusByEmployeeId(employeeId)); 18 } 19 20 public Guid EmployeeId { get; private set; } 21 public string EmployeeNo { get; private set; } 22 public string Name { get; private set; } 23 public string Password { get; private set; } 24 public string Email { get; private set; } 25 public string Phone { get; private set; } 26 public bool Enabled { get; set; } 27 public bool IsAdministrator { get; private set; } 28 public DateTime RegisterDate { get; private set; } 29 public string Remark { get; private set; } 30 public string IpLimitation { get; set; } 31 public object Id 32 { 33 get { return EmployeeId; } 34 } 35 }