C# 关于引用类型的类外只读属性
类内的只读属性不能更改的是他的指向
,例如,容器类List
,如果是只内部可写,外部可读,只有类内部可以更改 List
字段的指向赋值,外部不能。而类外get
到它的指向值后,是可以对它进行Add
等操作的,因为没有更改它的指向。
有点绕,估计没讲清我想要说什么。O(∩_∩)O
using System;
using System.Collections.Generic;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Test test = new Test();
List<string> tlist = test.TList;
tlist.Add("Lily"); // 增加两个
tlist.Add("Lucy");
foreach (var item in tlist)
{
Console.WriteLine(item);
}
List<string> nlist = new List<string>(); // 新实例
// test.TList = nlist; // 不能从新指向
tlist = nlist; // 这个和test实例不相干,当然可以改指向
Console.Read();
}
}
class Test
{
public List<string> TList { get; private set; }
public Test()
{
this.TList = new List<string>();
this.TList.Add("Tom");
}
}
}
输出:
Tom
Lily // 后面这两个是可以增加的。
Lucy
下面这样重新指向一个新实例是不行的。
List<string> nlist = new List<string>(); // 新实例
test.TList = nlist; // 不能从新指向
test.TList = nlist; // 不能从新指向
,外部只读不能更改指向。
再看:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
Student stu = new Student() {Name = "Hi", Age = 1 };
Console.WriteLine(stu.Name + "\n" + stu.Age);
Student stu1 = stu;
stu1.Name = "Hello";
stu1.Age = 10;
Console.WriteLine("\n" + stu.Name + "\n" + stu.Age);
Console.ReadKey();
}
}
class Student
{
public string Name { get; set; }
public int Age { get; set; }
}
}
输出:
Hi
1
Hello
10
只要不更改引用的指向,其应用内部的属性如果是可读可写的话,还是可以修改值的。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了