다음을 통해 공유


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

속성
규칙 ID CA1857
제목 매개 변수는 최적의 성능을 위해 상수를 기대합니다.
범주 성능
수정 사항이 호환성을 깨뜨리는지 여부 또는 무중단인지 여부 주요 변경 아님
.NET 10에서 기본적으로 사용하도록 설정 경고로서
적용 가능한 언어 C#

원인

잘못된 인수가 주석이 추가된 매개 변수에 전달됩니다 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

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