C#将相同的变量传递给两个“out”参数

时间:2017-08-28 16:14:08

标签: c#

“user1”和“user2”在下面的示例中指向相同的引用是否正常?

我知道我将相同的变量'notUsed'传递给两个参数,但它还没有实例化,因此它不包含对任何内容的引用。看到user1和user2相互链接,我感到非常震惊。

static void CheckPasswords(out string user1, out string user2)
{
    user1 = "A";
    user2 = "B";

    Console.WriteLine("user1: " + user1);
    Console.WriteLine("user2: " + user2);
}

public static void Main()
{
    string notUsed;
    CheckPasswords(out notUsed, out notUsed);
}

控制台显示:

user1: B
user2: B

3 个答案:

答案 0 :(得分:10)

使用out关键字时,您可以通过引用传递。 (https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/out-parameter-modifier)由于您是通过引用传递的,因此user1user2都指向同一个变量。因此,当您更新一个时,它会更新另一个。

答案 1 :(得分:3)

您正在通过引用传递变量。此外,方法中的赋值顺序很重要 - 如此处所写的变量最后将包含“B”。如果你反转它们,那么就会产生“A”。

比较

user1 = "A"; // notused now contains "A"
user2 = "B"; // notused now contains "B"
// method ends with the variable notused containing "B"

对战:

user2 = "B"; // notused now contains "B"
user1 = "A"; // notused now contains "A"
// method ends with the variable notused containing "A"

答案 2 :(得分:1)

此:

CheckPasswords(out notUsed, out notUsed);

没有将notUsed内容传递给方法(就像在没有使用out参数的方法中那样),它会传递引用notUsed方法。事实上,两次相同的参考。如你所说,此时notUsed本身并不包含引用,但这并不重要 - 我们对内容没有做任何事情,事实上,我们并不关心,因为我们正在通过它为out。然后这个:

user1 = "A";

执行一些特殊操作,因为user1不是string参数 - 它是out string参数。它不是为某个本地user1分配值,而是为user1指向的值指定值 - 在本例中为notUsed。此时,notUsed包含对"A"的引用。然后这个:

user2 = "B";

执行相同的操作,但通过其他参数 - 它会将"B"的引用分配给notUsed。然后是这两行:

Console.WriteLine("user1: " + user1);
Console.WriteLine("user2: " + user2);

不检索任何局部变量的内容,而是检索notUsed中的值,因为user1user2都指向它。所以,当然,你会得到"B"两次。

这并不比这段代码更令人震惊:

class User {
    public string Name { get; set; }
}

void NotMagic(User user1, User user2) {
    user1.Name = "A";
    user2.Name = "B";

    Console.WriteLine("user1.Name = " + user1.Name);
    Console.WriteLine("user2.Name = " + user2.Name);
}

void Main() {
    User user = new User();
    NotMagic(user, user);
}

如果打印B两次,你可能不会感到惊讶。 NotMagic中有两个不同的参数并不意味着它们不能同时指向同一个事物。与outref参数相同,只是语法会为您隐藏额外的间接。