public class MyClass
{
public MyClass(..., IList<MyType> items)
{
...
_myReadOnlyList = new List<MyType>(items).AsReadOnly();
}
public IList<MyType> MyReadOnlyList
{
get { return _myReadOnlyList; }
}
private IList<MyType> _myReadOnlyList
}
if you're going to return your collection, either return a copy or a read-only version (for example, using 数组列表,只读 or similar - you can combine this with the previous point and 商店 a read-only copy to be returned when callers access it), return an enumerator, or use some other method/property that allows read-only access into the collection
The original question and answer date from the end of 2008, there is now a System.Collections.Immutable 命名空间 that I believe dates from the earliest .NET Core (1.0) . The namespace is still not available in .NET Standard (current version 2.1) and .NET framework (current version 4.8). This namespace has lots of immutable collections including the 不可变列表, which is asked about in the original question. However, I believe the System.Collections.Immutable namespace may appear in .NET 5 which is at release candidate 2 at the moment.
public record Customer(string FirstName, string LastName, IEnumerable<string> Items);
//...
var person = new Customer("Test", "test", new List<string>() { "Test1", "Test2", "Test3" });
// you can't change anything within person variable
// person.FirstName = "NewName";