这个布尔值的返回有什么问题?

问题描述 投票:0回答:1

输入布尔未设置为 boolToSet

    bool SwitchToOpposite(bool boolToSet)
    {
        if (boolToSet)
            boolToSet = false;
        else
            boolToSet = true;
        return boolToSet;
    }

我需要做什么才能返回 boolToSet?

c# boolean return
1个回答
1
投票

如果你想在一个类中设置

boolToSet
fieldproperty,使用
this.
前缀来解决这个字段/属性,例如

// Field within then class
private boolToSet;   

// A method to change boolToSet field
bool SwitchToOpposite(bool boolToSet)
{
    // We chech the argument passed  
    if (boolToSet)
        // but change the field which belongs to object
        this.boolToSet = false;
    else
        this.boolToSet = true;

    // we return changed value, not the argument of the method  
    return this.boolToSet;
}

注意,您可以简化代码:

// A method to change boolToSet field
bool SwitchToOpposite(bool boolToSet)
{
    // Set (NOT boolToSet) to boolToSet field and return it
    return this.boolToSet = !boolToSet;
}
© www.soinside.com 2019 - 2024. All rights reserved.