CA2246:請勿在相同的陳述式中指派符號及其成員

屬性
規則識別碼 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;'
    }
}

隱藏警告的時機

請勿隱藏此規則的違規。

另請參閱