[英]Why I am not getting error with ref keyword
According to definition, ref
keyword must be initialized before passing. 根据定义,
ref
关键字必须在传递之前初始化。 while out
parameters must be initialized before returning from the function. out
参数必须在从函数返回之前初始化。
Below is my snippet. 以下是我的片段。
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.
}
Now while calling the methods. 现在在调用方法时。
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.
在尝试调用TestRef()时的上述调用中,我没有初始化name参数。 But as per my understanding ref parameter must be initialized before passing.
但根据我的理解,ref参数必须在传递之前初始化。
It builds & run with no errors. 它构建和运行没有错误。
TestOut
guarantees that name
variable will be initialized when method will finish execution TestOut
保证在方法完成执行时初始化name
变量
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
尽管作为out参数传递的变量在传递之前不必初始化,但是在方法返回之前需要调用方法来赋值
An argument that is passed to a ref parameter must be initialized before it is passed.
传递给ref参数的参数必须在传递之前初始化。 This differs from out parameters, whose arguments do not have to be explicitly initialized before they are passed.
这与out参数不同,out参数在传递之前不必显式初始化。 For more information, see out.
有关更多信息,请参阅。
Reorder the method calls and you will see the behavior you expect. 重新排序方法调用,您将看到您期望的行为。
Calling the TestOut
method first guarantees the initialization of the name
variable. 首先调用
TestOut
方法可以保证name
变量的初始化。 Reorder the method calls and you will see the behavior you expect. 重新排序方法调用,您将看到您期望的行为。
comment out the line TestOut(out name);//fineTestOut(out name);//fine You will get error for the following lines string name; 注释掉TestOut(out name); // fineTestOut(out name); // fine你将得到以下行字符串名称的错误; TestRef(ref name) // why not throwing error.
TestRef(ref name)//为什么不抛出错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.