C#调用方法和变量范围

nzs*_*ott 2 c#

为什么卡片会在下方更换?让我感到困惑..理解通过ref传递哪个工作正常..但是当传递数组时并没有像我预期的那样做.在.NET3.5SP1下编译

非常感谢

void btnCalculate_Click(object sender, EventArgs e)
{
    string[] cards = new string[3];
    cards[0] = "old0";
    cards[1] = "old1";
    cards[2] = "old2";
    int betResult = 5;
    int position = 5;
    clsRules myRules = new clsRules();
    myRules.DealHand(cards, betResult, ref position);  // why is this changing cards!
    for (int i = 0; i < 3; i++)
        textBox1.Text += cards[i] + "\r\n";  // these are all new[i] .. not expected!

    textBox1.Text += "betresult " + betResult.ToString() + "\r\n";  // this is 5 as expected
    textBox1.Text += "position " + position.ToString() + "\r\n"; // this is 6 as expected
}

public class clsRules
{
    public void DealHand(string[] cardsInternal, int betResultInternal, ref int position1Internal)
    {
        cardsInternal[0] = "new0";
        cardsInternal[1] = "new1";
        cardsInternal[2] = "new2";

        betResultInternal = 6;
        position1Internal = 6;
    }
}
Run Code Online (Sandbox Code Playgroud)

Jar*_*Par 5

数组是引用类型,简而言之,数组的值不直接包含在变量中.相反,变量指的是值.希望以下代码能够更好地解释这一点(List<T>也是一种引用类型).

List<int> first = new List<int>()( new int[] {1,2,3});
List<int> second = first;
first.Clear();
Console.WriteLine(second.Count);  // Prints 0
Run Code Online (Sandbox Code Playgroud)

在这种情况下List<int>,在第一行上创建了一个由变量first引用.第二行不会创建新列表,而是创建名为second的第二个变量,该变量引用与第一个相同的List<int>对象.此逻辑适用于所有引用类型.

当您将变量卡传递给方法时,您不会传递完整数组的副本,而是传递变量卡的副本.此副本引用与原始卡相同的阵列对象.因此,通过原始引用可以看到对数组所做的任何修改.