1. 程式人生 > 其它 >C# 關於引用型別的類外只讀屬性

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

只要不更改引用的指向,其應用內部的屬性如果是可讀可寫的話,還是可以修改值的。