【发布时间】:2012-08-26 15:31:33
【问题描述】:
class OutReturnExample
{
static void Method(out int i, out string s1, out string s2)
{
i = 44;
s1 = "I've been returned";
s2 = null;
}
static void Main()
{
int value;
string str1, str2;
Method(out value, out str1, out str2);
// value is now 44
// str1 is now "I've been returned"
// str2 is (still) null;
}
我是 C# 新手,正在学习修饰符。我遇到了this snippet on MSDN。
我知道out 在这里对于 int 原始变量很有用,但是对于字符串变量,即使没有 out 修饰符,引用也会传递给被调用的方法,对吧?
【问题讨论】:
-
不,不对。如果字符串参数未标记为 out,则 s1 和 s2 将被视为局部变量。考虑 ref 和 out,因为您不是使用引用本身,而是使用对引用的引用。
-
对于引用类型(例如字符串),引用将按值传递。这意味着您可以更改实例的内容,但不能更改引用本身。对于字符串,您甚至无法更改内容,因为它们是不可变的。