【问题标题】:Boolean as methods parameter is not changing state布尔作为方法参数不改变状态
【发布时间】:2019-05-28 15:43:26
【问题描述】:

我想更改函数中布尔值的状态。我的函数有 4 个参数,第四个是布尔值,默认为 true,但我想在函数内部将其状态更改为 false。

我正在调用我的方法,

SlotCheck("Red", "red_small_c", puzzle_9, GameControl.control.scoreRedGems, GameControl.control.stone_9);

GameControl.control.stone_9 默认为 true。一旦 visibilty 设置为 false,它应该变为 false ..但这并没有发生...stone_9 保持为真。

public void SlotCheck(string gemColor,string slotColor,GameObject puzzleStuk,int scoreGem,bool Visibility)
{
    if (DragHandler2.itemBegingDragged.name.Contains(gemColor) && DragHandler2.itemBegingDragged.transform.parent.name == slotColor)
    {
        Debug.Log(DragHandler2.itemBegingDragged.name);
        Visibility=false;
        puzzleStuk.SetActive(visibility);
        Debug.Log(GameControl.control.stone_9);    //true
        DragHandler2.itemBegingDragged.SetActive(false);

    }

我希望 GameControl.control.stone_9 将其状态更改为 false,因为我将参数(可见性)的状态更改为 false,但 GameControl.control.stone_9 保持为 true。

【问题讨论】:

  • 使用ref传递布尔值,你需要这样做的原因是c#有引用访问,并且可以修改实际的布尔值,而不是克隆参数。

标签: c# methods boolean


【解决方案1】:

我相信您的印象是更改参数的值将反映给调用者(您的第一个代码块)。除非您对参数/参数使用ref 或out,否则情况并非如此。只要GameControl.control.stone_9 是字段而不是属性,这将起作用。

简而言之,除非使用这些关键字,否则参数是按值传递的。 (对于引用类型也是如此,但它有点复杂,因为复制的是引用,而不是实际的对象本身)

其他答案已经解释了语法(需要对参数和参数使用ref。)

还有一点建议,千万不要将变量或参数大写,因为大多数 C# 读者会将它们视为包含类中的属性,从而导致混淆。

【讨论】:

  • 非常感谢先生,我真的不知道裁判和出局。赞赏
【解决方案2】:

如果你想改变一个 Method 内部变量的值,你应该通过 ref 来定义它:

public void SlotCheck(string gemColor,string slotColor,GameObject puzzleStuk,int scoreGem,ref bool Visibility)
{
   //method stuff
     Visibility = false;
}

然后像这样调用你的方法:

SlotCheck("Red", "red_small_c", puzzle_9, GameControl.control.scoreRedGems, ref GameControl.control.stone_9);

【讨论】:

  • 好吧,我就是说你说的,变量名无所谓,参数随便命名
【解决方案3】:

1-SlotCheck中的四个参数应该是ref bool Visibility

或者

在if 语句中你应该这样做

GameControl.control.stone_9 = false;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-02
    • 1970-01-01
    • 1970-01-01
    • 2020-03-16
    • 1970-01-01
    相关资源
    最近更新 更多