gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:54:33 25 4
gpt4 key购买 nike

根据定义,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.

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

关于c# - 为什么我没有收到 ref 关键字的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41807191/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com