CA2227: Propriedades da coleção devem ser somente leitura

TypeName

CollectionPropertiesShouldBeReadOnly

CheckId

CA2227

<strong>Categoria</strong>

Microsoft.Usage

Alteração significativa

Quebrando

Causa

Uma propriedade gravável visível externamente é um tipo que implementa System.Collections.ICollection. Arrays, indexadores (propriedades com o nome 'Item') e conjuntos de permissão são ignorados pela regra.

Descrição da regra

Uma propriedade de coleção gravável permite que um usuário substituir a coleção com uma coleção completamente diferente. Uma propriedade somente leitura pára a coleção seja substituída, mas ainda permite que os membros individuais sejam definidas. Se a substituição de coleção é uma meta, o padrão de design preferencial é incluir um método para remover todos os elementos da coleção e um método para preencher a coleção. Consulte o Clear e AddRange métodos para a System.Collections.ArrayList classe para obter um exemplo deste padrão.

Suportam a propriedades somente leitura que são conjuntos binários e serialização de XML. O System.Xml.Serialization.XmlSerializer classe tem requisitos específicos para tipos que implementam ICollection e System.Collections.IEnumerable para ser serializável.

Como corrigir violações

Para corrigir uma violação desta regra, verifique a propriedade somente leitura e, se o projeto requer a ele, adicionar métodos para limpar e preencher a coleção.

Quando suprimir avisos

Não suprimir um aviso da regra.

Exemplo

O exemplo a seguir mostra um tipo de uma propriedade de coleção gravável e como a coleção pode ser substituída diretamente. Além disso, a forma preferencial de substituição de uma propriedade de coleção somente leitura usando o Clear e AddRange métodos é mostrado.

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);
}

Regras relacionadas

CA1819: Propriedades não devem retornar arrays