CA1857:參數預期常數以獲得最佳效能

屬性
規則識別碼 CA1857
標題 參數預期常數以達到最佳效能
類別 效能
修正程式是中斷或非中斷 不中斷
預設在 .NET 8 中啟用 作為警告

原因

不正確引數會傳遞至以 ConstantExpectedAttribute 標注的參數。

檔案描述

此規則旗標會放在您的程式碼中,您可以在其中:

如何修正違規

更正您的程式碼,如您收到的特定錯誤訊息所指示。

範例 1 (預期屬性)

下列程式碼片段顯示 CA1857 的違規:

public interface I1<T>
{
    T M1(T operand1, [ConstantExpected] T operand2);
}

public class C1 : I1<int>
{
    public int M1(int operand1, int operand2) =>
        throw new NotImplementedException();
}

下列程式碼片段會修正違規:

public interface I1<T>
{
    T M1(T operand1, [ConstantExpected] T operand2);
}

public class C1 : I1<int>
{
    public int M1(int operand1, [ConstantExpected] int operand2) =>
        throw new NotImplementedException();
}

範例 2 (常數不常數)

下列程式碼片段顯示 CA1857 的違規:

static void M1(int i) => M2(i);
static void M2([ConstantExpected] int i) { }

下列程式碼片段會修正違規:

static void M1([ConstantExpected] int i) => M2(i);
static void M2([ConstantExpected] int i) { }

範例 3 (無效常數)

下列程式碼片段顯示 CA1857 的違規:

static void M1() => M2((string)(object)20);
static void M2([ConstantExpected] string s) { }

下列程式碼片段會修正違規:

static void M1() => M2("20");
static void M2([ConstantExpected] string s) { }

範例 4 (界限外常數)

下列程式碼片段顯示 CA1857 的違規:

static void M1() => M2(5);
static void M2([ConstantExpected(Min = 3, Max = 4)] int i) { }

下列程式碼片段會修正違規:

static void M1() => M2(4);
static void M2([ConstantExpected(Min = 3, Max = 4)] int i) { }

隱藏警告的時機

如果效能不相關,請放心地隱藏此規則的警告。

隱藏警告

如果您只想要隱藏單一違規,請將預處理器指示詞新增至原始程式檔以停用,然後重新啟用規則。

#pragma warning disable CA1857
// The code that's violating the rule is on this line.
#pragma warning restore CA1857

若要停用檔案、資料夾或專案的規則,請在組態檔 中將其嚴重性設定為 。 none

[*.{cs,vb}]
dotnet_diagnostic.CA1857.severity = none

如需詳細資訊,請參閱 如何隱藏程式碼分析警告