Share via


CA2246: 동일한 문에 기호와 해당 멤버를 할당하지 마세요.

속성
규칙 ID CA2246
타이틀 동일한 문에 기호 및 해당 멤버를 할당하지 마세요.
범주 사용 현황
수정 사항이 주요 변경인지 여부 주요 변경 아님
.NET 8에서 기본적으로 사용 제안 사항

원인

동일한 문에 할당된 기호 및 해당 멤버. 예시:

// 'a' and 'a.Field' are assigned in the same statement
a.Field = a = b;

규칙 설명

동일한 문에서는 기호 및 해당 멤버(필드 또는 속성)를 할당하지 않는 것이 좋습니다. 멤버 액세스가 할당 전 기호의 이전 값을 사용하거나 해당 문에 있는 할당의 새 값을 사용해야 했는지 분명하지 않습니다. 명확성을 위해 다중 할당 문은 둘 이상의 단순 대입문으로 분할되어야 합니다.

위반 문제를 해결하는 방법

위반 문제를 해결하려면 다중 할당 문을 둘 이상의 단순 대입문으로 분할합니다. 예를 들어 다음 코드 조각은 규칙 위반 및 사용자 의도에 따라 위반을 해결하는 몇 가지 방법을 보여 줍니다.

public class C
{
    public C Field;
}

public class Test
{
    public void M(C a, C b)
    {
        // Let us assume 'a' points to 'Instance1' and 'b' points to 'Instance2' at the start of the method.
        // It is not clear if the user intent in the below statement is to assign to 'Instance1.Field' or 'Instance2.Field'.
        // CA2246: Symbol 'a' and its member 'Field' are both assigned in the same statement. You are at risk of assigning the member of an unintended object.
        a.Field = a = b;
    }
}
public class C
{
    public C Field;
}

public class Test
{
    public void M(C a, C b)
    {
        // Let us assume 'a' points to 'Instance1' and 'b' points to 'Instance2' at the start of the method.
        // 'Instance1.Field' is intended to be assigned.
        var instance1 = a;
        a = b;
        instance1.Field = a;
    }
}
public class C
{
    public C Field;
}

public class Test
{
    public void M(C a, C b)
    {
        // Let us assume 'a' points to 'Instance1' and 'b' points to 'Instance2' at the start of the method.
        // 'Instance2.Field' is intended to be assigned.
        a = b;
        b.Field = a; // or 'a.Field = a;'
    }
}

경고를 표시하지 않는 경우

이 규칙에서는 위반을 표시해야 합니다.

참고 항목