天天看點

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