次の方法で共有


CA1802: 適切な場所にリテラルを使用します

TypeName

UseLiteralsWhereAppropriate

CheckId

CA1802

[カテゴリ]

Microsoft.Performance

互換性に影響する変更点

なし

原因

フィールドが static および readonly (Visual Basic では Shared および ReadOnly) として宣言され、コンパイル時に計算できる値によって初期化されています。

規則の説明

宣言型の静的コンストラクターが呼び出されると、staticreadonly フィールドの値は実行時に計算されます。staticreadonly フィールドが宣言されるときに初期化され、静的コンストラクターが明示的に宣言されなかった場合、コンパイラは静的コンストラクターを出力してフィールドを初期化します。

const フィールドの値は、コンパイル時に計算され、メタデータに格納されます。その結果、staticreadonly フィールドに比べて実行時のパフォーマンスが向上します。

対象フィールドに代入された値はコンパイル時に計算できるので、宣言を const フィールドに変更して、値が実行時ではなくコンパイル時に計算されるようにします。

違反の修正方法

この規則の違反を修正するには、static 修飾子および readonly 修飾子を const 修飾子で置き換えます。

警告を抑制する状況

パフォーマンスを重視しない場合は、この規則による警告を抑制するか、または規則を無効にしても安全です。

使用例

この規則に違反している型 UseReadOnly と、規則に適合する型 UseConstant を次の例に示します。

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