为什么我没有收到 ref 关键字的错误

Why I am not getting error with ref keyword

根据定义,ref关键字必须在传递前进行初始化。而 out 参数必须在从函数返回之前初始化。

下面是我的代码片段。

   public void TestRef(ref string n)
    {

    }

    public void TestOut(out string n)
    {

        n = "Hello"; //if I don't initialize, I gets compile time error. & That's right.

    }

现在正在调用方法。

string name;
TestOut(out name);//fine
TestRef(ref name) // why not throwing error.

In the above calls when trying to call TestRef() I have not initialized name parameter. But as per my understanding ref parameter must be initialized before passing.

构建 运行 没有错误。

TestOut 保证 name 变量将在方法完成执行时初始化

参见out关键字

Although variables passed as out arguments do not have to be initialized before being passed, the called method is required to assign a value before the method returns

ref

An argument that is passed to a ref parameter must be initialized before it is passed. This differs from out parameters, whose arguments do not have to be explicitly initialized before they are passed. For more information, see out.

重新排序方法调用,您将看到预期的行为。

调用TestOut方法首先保证name变量的初始化。 重新排序方法调用,您将看到预期的行为。

注释掉该行 TestOut(out name);//fineTestOut(out name);//很好 您将收到以下行的错误 字符串名称; TestRef(ref name) // 为什么不抛出错误。