Compartir a través de


CA2227: Las propiedades de la colección deben ser de solo lectura

Nombre de tipo

CollectionPropertiesShouldBeReadOnly

Identificador de comprobación

CA2227

Categoría

Microsoft.Usage

Cambio problemático

Motivo

Una propiedad de escritura visible externamente es un tipo que implementa System.Collections.ICollection.La regla omite las matrices, los indizadores (propiedades con el nombre 'Item') y los conjuntos de permisos.

Descripción de la regla

Una propiedad de colección de escritura permite al usuario reemplazar la colección por otra completamente diferente.Una propiedad de sólo lectura impide que la colección se reemplace, pero sí permite establecer miembros individuales.Si el objetivo es reemplazar la colección, el modelo de diseño más indicado es incluir un método para quitar todos los elementos de la colección y otro método para volver a rellenarla.Vea los métodos Clear y AddRange de la clase System.Collections.ArrayList para obtener un ejemplo de este modelo.

La serialización binaria y XML admiten propiedades de sólo lectura que son colecciones.La clase System.Xml.Serialization.XmlSerializer tiene requisitos concretos para los tipos que implementan ICollection y System.Collections.IEnumerable, a fin de ser serializable.

Cómo corregir infracciones

Para corregir una infracción de esta regla, haga que la propiedad sea de sólo lectura y, si el diseño lo exige, agregue métodos para borrar su contenido y rellenarla de nuevo.

Cuándo suprimir advertencias

No suprima las advertencias de esta regla.

Ejemplo

El ejemplo siguiente muestra un tipo con una propiedad de colección de escritura y muestra cómo se puede reemplazar la colección directamente.Además, se muestra la manera más adecuada de reemplazar una propiedad de colección de sólo lectura, utilizando los métodos Clear y AddRange.

Imports System
Imports System.Collections

Namespace UsageLibrary

   Public Class WritableCollection

      Dim strings As ArrayList

      Property SomeStrings As ArrayList
         Get
            Return strings
         End Get

         ' Violates the rule.
         Set
            strings = Value
         End Set
      End Property

      Sub New()
         strings = New ArrayList( _
            New String() {"IEnumerable", "ICollection", "IList"} )
      End Sub

   End Class

   Class ViolatingVersusPreferred

      Shared Sub Main()
         Dim newCollection As New ArrayList( _
            New String() {"a", "new", "collection"} )

         ' strings is directly replaced with newCollection.
         Dim collection As New WritableCollection()
         collection.SomeStrings = newCollection

         ' newCollection is added to the cleared strings collection.
         collection.SomeStrings.Clear()
         collection.SomeStrings.AddRange(newCollection)
      End Sub

   End Class

End Namespace
using System;
using System.Collections;

namespace UsageLibrary
{
   public class WritableCollection
   {
      ArrayList strings;

      public ArrayList SomeStrings
      {
         get { return strings; }

         // Violates the rule.
         set { strings = value; }
      }

      public WritableCollection()
      {
         strings = new ArrayList(
            new string[] {"IEnumerable", "ICollection", "IList"} );
      }
   }

   class ReplaceWritableCollection
   {
      static void Main()
      {
         ArrayList newCollection = new ArrayList(
            new string[] {"a", "new", "collection"} );

         // strings is directly replaced with newCollection.
         WritableCollection collection = new WritableCollection();
         collection.SomeStrings = newCollection;

         // newCollection is added to the cleared strings collection.
         collection.SomeStrings.Clear();
         collection.SomeStrings.AddRange(newCollection);
      }
   }
}
using namespace System;
using namespace System::Collections;

namespace UsageLibrary
{
   public ref class WritableCollection
   {
   public:
      // Violates the rule.
      property ArrayList^ SomeStrings;

      WritableCollection()
      {
         SomeStrings = gcnew ArrayList(
            gcnew array<String^> {"IEnumerable", "ICollection", "IList"} );
      }
   };
}

using namespace UsageLibrary;

void main()
{
   ArrayList^ newCollection = gcnew ArrayList(
      gcnew array<String^> {"a", "new", "collection"} );

   // strings is directly replaced with newCollection.
   WritableCollection^ collection = gcnew WritableCollection();
   collection->SomeStrings = newCollection;

   // newCollection is added to the cleared strings collection.
   collection->SomeStrings->Clear();
   collection->SomeStrings->AddRange(newCollection);
}

Reglas relacionadas

CA1819: Las propiedades no deberían devolver matrices