Compartilhar via


Use literais onde for apropriado

TypeName

UseLiteralsWhereAppropriate

CheckId

CA1802

Category (Categoria)

Microsoft.desempenho

Quebrando alterar

Não separável

Causa

Um campo é declarado static e readonly (Shared e ReadOnly no Visual Basic) e é inicializada com um valor que seja computáveis em time de compilar.

Descrição da regra

The value of a staticreadonly field is computed at runtime when the static constructor for the declaring type is called.If the staticreadonly field is initialized when it is declared and a static constructor is not declared explicitly, the compiler emits a static constructor to initialize the field.

The value of a const field is computed at compile time and stored in the metadata, which increases runtime performance when compared to a staticreadonly field.

Como o valor atribuído ao campo de destino é computáveis em time de compilar, altere a declaração para um const campo para que o valor é calculado em time de compilar em vez de em time de execução.

Como corrigir violações

Para corrigir uma violação dessa regra, substitua o static e readonly modificadores com o const modificador.

Quando suprimir avisos

É seguro eliminar um aviso da regra ou desabilitar a regra inteiramente, se o desempenho não for uma preocupação.

Exemplo

O exemplo a seguir mostra um tipo, UseReadOnly, que viola a regra e um tipo UseConstant, que satisfaz a regra.

Imports System

Namespace PerformanceLibrary

   ' This class violates the rule.
   Public Class UseReadOnly

      Shared ReadOnly x As Integer = 3
      Shared ReadOnly y As Double = x + 2.1
      Shared ReadOnly s As String = "readonly"

   End Class

   ' This class satisfies the rule.
   Public Class UseConstant

      Const x As Integer = 3
      Const y As Double = x + 2.1
      Const s As String = "const"

   End Class

End Namespace
using System;

namespace PerformanceLibrary
{
   // This class violates the rule.
   public class UseReadOnly
   {
      static readonly int x = 3;
      static readonly double y = x + 2.1;
      static readonly string s = "readonly";
   }

   // This class satisfies the rule.
   public class UseConstant
   {
      const int x = 3;
      const double y = x + 2.1;
      const string s = "const";
   }
}