Un setter privato per una lista, Collezione, ecc significa che l'intero elenco non può essere sostituito da parte dei consumatori, ma non fa nulla per proteggere i membri pubblici della lista.
Ad esempio:
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
}
}
Al fine di evitare che i consumatori, che modifica i membri della lista si potrebbe esporlo come sola lettura di interfaccia, come ad esempio IEnumerable<string>
, ReadOnlyCollection<string>
, o chiamando List.AsReadOnly()
all'interno della dichiarazione classe.
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
}
}
Si aggiunge un accessorio al set. cioè: {get; set privato; } – phillip
Devi essere più specifico. Vuoi impedire ai client di modificare il riferimento a 'List' o vuoi impedire ai client di aggiungere o rimuovere elementi dalla lista? –
Voglio impedire ai client di modificare il riferimento Elenco. – anmarti