簡體   English   中英

如何更改 c# 中的 for 循環參數調用的 boolean 數組的值

[英]How to change the value of a boolean array that is called by a for loop parameter in c#

我有以下問題:

在 for 循環中,我嘗試調用來自另一個 class 的數組,並且我通過參數將其設為公共,當我想為參數分配值時,它不會反映在數組中。

1)。 使用參數調用數組是否正確?

2)。 我在哪里失敗了,為什么我分配給矩陣的值“真”沒有分配?

static public void VentanaReserva(System.Windows.Forms.Button button , bool Valor1  )
        {
            if (Valor1 == false)
            {
                button.BackColor = System.Drawing.Color.Red;
                Valor1 = true;     **//This is where you assign the value of true** -----

                MessageBoxBase messageBoxBase = new MessageBoxBase();

                messageBoxBase.ShowDialog();
                ValorCancha.SumaDeCanchaPequeña();

            }

 private void button1_Click(object sender, EventArgs e)//this is the place where I assign the parameters that are in another class
        {

            EstadoDeReserva.VentanaReserva(button1, ValorCancha.Visualizar[0,1]);
         }

我假設你想做這樣的事情:

var myBools = new bool[10];
for(var i = 0; i < myBools.Length; i++){
    MyMethod(myBools[i]);
}
void MyMethod(bool myBool){
    myBool = !myBool;
}

這是行不通的,因為像 bool 這樣的原始類型是傳遞的 因此,為任何參數分配新值不會影響原始值。

解決這個問題的最簡單方法是返回新值並分配它:

var myBools = new bool[10];
for(var i = 0; i < myBools.Length; i++){
    myBools[i] = MyMethod(myBools[i]);
}
bool MyMethod(bool myBool){
    return !myBool;
}

也可以通過引用傳遞參數,以及ref return 和 ref local ,但這不是我推薦的,除非你有一些非常具體的用例。 如果方法接受一些參數、返回一些值並且沒有任何副作用,則它們往往是最容易使用的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM