C#中的'out'修饰符

Ziy*_*ang 4 c# out

可能重复:
C# - 引用类型仍然需要通过ref?

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;
    }
Run Code Online (Sandbox Code Playgroud)

我是C#的新手并且学习了修饰符.我在MSDN上看到了这个片段.

我理解out这对于int原始变量很有用,但对于字符串变量,即使没有out修饰符,引用也会传递给被调用的方法,对吧?

Hen*_*man 10

即使没有out修饰符,引用也会传递给被调用的方法,对吧?

是的,但没有out他们将不会被传回:

void M(string s1, out string s2)
{
    s1 = "one";
    s2 = "two";
}

void Main()
{
    string s = "hello", t = "world";
    // s = "hello"
    // t = "world"
    M(s, out t);
    // s = "hello"
    // t = "two"
}
Run Code Online (Sandbox Code Playgroud)

string被设计为不可变的.您可能正在考虑可变引用类型:

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

void Main()
{
    var p = new Person { Name = "Homer" };
    // p != null
    // p.Name = "Homer"
    M2(p);
    // p != null
    // p.Name = "Bart"
}

void M2(Person q)
{
    q.Name = "Bart";   // q references same object as p
    q = null;          // no effect, q is a copy of p
}
Run Code Online (Sandbox Code Playgroud)