Jon*_*eet 19

对于来电者:

  • 对于ref参数,必须已经明确赋值变量
  • 对于out参数,变量不必明确赋值,但将在方法返回之后

对于方法:

  • REF参数开始了明确分配,并且不具有任何价值分配给它
  • out参数不会从明确分配开始,并且您必须确保无论何时返回(没有例外)它都将被明确分配

所以:

int x;
Foo(ref x); // Invalid: x isn't definitely assigned
Bar(out x); // Valid even though x isn't definitely assigned
Console.WriteLine(x); // Valid - x is now definitely assigned

...

public void Foo(ref int y)
{
    Console.WriteLine(y); // Valid
    // No need to assign value to y
}

public void Bar(out int y)
{
    Console.WriteLine(y); // Invalid: y isn't definitely assigned
    if (someCondition)
    {
        // Invalid - must assign value to y before returning
        return;
    }
    else if (someOtherCondition)
    {
        // Valid - don't need to assign value to y if we're throwing
        throw new Exception();
    }
    else
    {
        y = 10;
        // Valid - we can return once we've definitely assigned to y
        return;
    }
}
Run Code Online (Sandbox Code Playgroud)