ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2021-09-28 08:34:20  阅读:181  来源: 互联网

标签:类外 指向 只读 C# List System TList test using


类内的只读属性不能更改的是他的指向,例如,容器类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

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

标签:类外,指向,只读,C#,List,System,TList,test,using
来源: https://www.cnblogs.com/huvjie/p/15346174.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有