Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Kiểm tra ArrayList có kích thước cố định trong C#

Giới thiệu

ArrayList mặc định kích thước động (IsFixedSize = false). Có thể tạo wrapper kích thước cố định bằng ArrayList.FixedSize(ArrayList) - wrapper này không cho phép Add/Remove/Clear nhưng cho phép sửa phần tử hiện có.

Ví dụ 1: Synchronized wrapper (không fixed size)

using System;
using System.Collections;

public class Demo
{
    public static void Main(String[] args)
    {
        ArrayList list1 = new ArrayList();
        list1.Add("One");
        list1.Add("Two");
        list1.Add("Three");
        list1.Add("Four");
        list1.Add("Five");
        
        Console.WriteLine("Elements in ArrayList...");
        foreach (string res in list1)
        {
            Console.WriteLine(res);
        }
        
        ArrayList list = ArrayList.Synchronized(list1);
        Console.WriteLine("Is ArrayList synchronized? = " + list.IsSynchronized);
        Console.WriteLine("Is ArrayList have a fixed size? = " + list.IsFixedSize);
    }
}

Kết quả

Elements in ArrayList...
One
Two
Three
Four
Five
Is ArrayList synchronized? = True
Is ArrayList have a fixed size? = False

Ví dụ 2: FixedSize wrapper

using System;
using System.Collections;

public class Demo
{
    public static void Main(String[] args)
    {
        ArrayList list1 = new ArrayList();
        list1.Add("ABC");
        list1.Add("BCD");
        list1.Add("CDE");
        list1.Add("DEF");
        list1.Add("EFG");
        list1.Add("GHI");
        list1.Add("HIJ");
        list1.Add("IJK");
        list1.Add("JKL");
        list1.Add("KLM");
        
        Console.WriteLine("Elements in ArrayList...");
        foreach (string res in list1)
        {
            Console.WriteLine(res);
        }
        
        ArrayList list = ArrayList.Synchronized(list1);
        Console.WriteLine("Is ArrayList synchronized? = " + list.IsSynchronized);
        
        ArrayList list2 = ArrayList.FixedSize(list1);
        Console.WriteLine("Is ArrayList have a fixed size? = " + list2.IsFixedSize);
    }
}

Kết quả

Elements in ArrayList...
ABC
BCD
CDE
DEF
EFG
GHI
HIJ
IJK
JKL
KLM
Is ArrayList synchronized? = True
Is ArrayList have a fixed size? = True

Đặc điểm FixedSize Wrapper

Thao tác ArrayList gốc FixedSize Wrapper
Add OK NotSupportedException
Remove/RemoveAt OK NotSupportedException
Clear OK NotSupportedException
Insert OK NotSupportedException
Indexer set [i] = value OK OK (chỉ sửa giá trị)
Count Thay đổi Cố định

So sánh các Wrapper

Wrapper IsFixedSize IsReadOnly IsSynchronized
ArrayList gốc false false false
ArrayList.FixedSize() true false false
ArrayList.ReadOnly() true true false
ArrayList.Synchronized() false false true

Khuyến nghị hiện đại

Dùng List<T> + IReadOnlyList<T> interface hoặc ImmutableList<T> thay vì FixedSize wrapper.