Share via


CA1857: 매개 변수는 최적의 성능을 위해 상수를 기대합니다.

속성
규칙 ID 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

자세한 내용은 방법: 코드 분석 경고 표시 안 함을 참조하세요.