当前位置:网站首页>NetCore-如何保证ICollection或List私有化不被外部修改?
NetCore-如何保证ICollection或List私有化不被外部修改?
2022-07-24 01:39:00 【Magical-Conch】
假如我们需要一个类的内部集合成员不被外部操作,应该怎么写?
public class UserMaster {
/// <summary>
/// 地址
/// </summary>
public ICollection<UserAddress> UserAddressList {
get; private set; }
public UserMaster()
{
}
}
// ..
var user = new UserMaster();
user.UserAddressList.Add(new UserAddress("照样能加进去"));
// ..
我们通过上面代码发现,通过private set访问器,外部还是可以通过UserAddressList来Add修改集合内容。
这个时候,就需要AsReadOnly来解决问题了,如下:
public class UserMaster {
/// <summary>
/// 地址
/// </summary>
private ICollection<UserAddress> UserAddressList {
get; private set; }
public UserMaster()
{
}
public ReadOnlyCollection<UserAddress> GetAddress()
{
return this.UserAddressList.ToList().AsReadOnly();
}
边栏推荐
- Review of HCIA
- Summary of HCIA knowledge points
- Database paradigm and schema decomposition
- Copying readable paths is not easy
- Location and path planning (lingo, matlab implementation)
- Computer room construction data
- Customer first | domestic Bi leader, smart software completes round C financing
- Hcip experiment
- Design of hospital wireless network system
- Arm architecture and programming 1 -- LED flashing (based on Baiwen arm architecture and programming tutorial video)
猜你喜欢

SCM learning notes 6 -- interrupt system (based on Baiwen STM32F103 series tutorials)

20220723 record an unexplained shutdown of SAP Oracle monitoring service

Thread pool interview

Cartland number---

医院综合布线

Arm architecture and programming 7 -- exceptions and interrupts (based on Baiwen arm architecture and programming tutorial video)

Research on retinal vascular segmentation based on GAN using few samples

Exchange 2013 SSL证书安装文档

HCIP第八天笔记

Hcip day 6 notes
随机推荐
Thread pool interview
[code case] website confession wall & to do list (including complete source code)
vantUI,Axiso,常见问题及使用:
数字签名技术简介
jenkins多任务并发构建
LiteSpeed Web服务器中安装SSL证书
HCIA知识点总结
Install SSL Certificate in Litespeed web server
Hcip day 5 notes
Introduction and environment construction of little bear sect
Jenkins multitâche construction simultanée
Troisième semaine d'été
医院无线网络系统设计
Hcip day 9 notes
SCM learning notes 9 -- Serial Communication (based on Baiwen STM32F103 series tutorials)
Hcip day 12 notes
Three document usage
How to solve the problem that the universal vision NVR device is connected to the easycvr platform and cannot be online after offline?
Hcip third day notes
Number of combinations....