vb List, Koleksiyon için özel ayarlayıcı tüm liste tüketiciler tarafından değiştirilemez anlamına gelir, ama bu listenin kamu üyelerini korumak için hiçbir şey yapmaz. Örneğin
:
Bir Salt Okunur arayüz olarak kalmasına neden listenin üyelerini değiştirerek tüketicileri önlemek amacıyla
public class MyClass
{
public IList<string> MyList {get; private set;}
public MyClass()
{
MyList = new List<string>(){"One","Two", "Three"};
}
}
public class Consumer
{
public void DoSomething()
{
MyClass myClass = new MyClass();
myClass.MyList = new List<string>(); // This would not be allowed,
// due to the private setter
myClass.MyList.Add("new string"); // This would be allowed, because it's
// calling a method on the existing
// list--not replacing the list itself
}
}
, böyle IEnumerable<string>
, ReadOnlyCollection<string>
olarak veya ilan dahilinde List.AsReadOnly()
arayarak sınıf.
public class MyClass
{
public IList<string> MyList {get; private set;}
public MyClass()
{
MyList = new List<string>(){"One","Two", "Three"}.AsReadOnly();
}
}
public class Consumer
{
public void DoSomething()
{
MyClass myClass = new MyClass();
myClass.MyList = new List<string>(); // This would not be allowed,
// due to the private setter
myClass.MyList.Add("new string"); // This would not be allowed, the
// ReadOnlyCollection<string> would throw
// a NotSupportedException
}
}
Kümeye bir erişim elemanı eklersiniz. yani: {get; özel set; } – phillip
Daha spesifik olmanız gerekir. İstemcilerin 'List' referansını değiştirmesini önlemek mi istiyorsunuz yoksa istemcilerin istemcilere öğe ekleyip çıkarmasını önlemek mi istiyorsunuz? –
İstemcinin Liste referansını değiştirmesini önlemek istiyorum. – anmarti