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;'
    }
}

何时禁止显示警告

请勿禁止显示此规则的冲突警告。

另请参阅