C# 关于引用类型的类外只读属性

类内的只读属性不能更改的是他的指向,例如,容器类List,如果是只内部可写,外部可读,只有类内部可以更改 List 字段的指向赋值,外部不能。而类外get到它的指向值后,是可以对它进行Add等操作的,因为没有更改它的指向。

有点绕,估计没讲清我想要说什么。~O(∩_∩)O~

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
32
33
34
35
36
37
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");
}
}
}

输出:

1
2
3
Tom
Lily // 后面这两个是可以增加的。
Lucy

下面这样重新指向一个新实例是不行的。

1
2
List<string> nlist = new List<string>();  // 新实例
test.TList = nlist; // 不能从新指向

test.TList = nlist; // 不能从新指向,外部只读不能更改指向。

再看:

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
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; }
}
}

输出:

1
2
3
4
5
Hi
1

Hello
10

只要不更改引用的指向,其应用内部的属性如果是可读可写的话,还是可以修改值的。

感谢支持!