为什么我需要在声明和调用中使用'ref'关键字.
void foo(ref int i)
{
}
Run Code Online (Sandbox Code Playgroud)
例如,考虑以上功能.如果我在没有ref关键字的情况下调用它
foo(k);
Run Code Online (Sandbox Code Playgroud)
它会给我错误:
必须使用'ref'关键字传递参数'1'
为什么仅仅在方法签名中指定它是不够的?
Gra*_*ton 12
这是因为ref表明参数应该通过引用传入.它类似于C++中的指针
例如;
void CalFoo()
{
var i=10;
foo(ref i); //i=11
}
void foo(ref int i)
{
i++;
}
Run Code Online (Sandbox Code Playgroud)
但
void CalFoo()
{
var i=10;
foo(i); //i=10
}
void foo(int i)
{
i++;
}
Run Code Online (Sandbox Code Playgroud)
我认为你可以同时foo(ref int)和foo(int)一个单独的类.所以如果你没有指定ref..编译器如何知道调用哪一个?
| 归档时间: |
|
| 查看次数: |
18155 次 |
| 最近记录: |