使用关键字时ref,调用代码需要初始化传递的参数,但是使用关键字out我们不需要这样做.
out到处使用?ref但不能使用的情况out?dtb*_*dtb 14
out是一种特殊形式,ref在调用之前不应该初始化引用的内存.
在这种情况下,C#编译器强制out在方法返回之前分配变量,并且在分配变量之前不使用该变量.
两个例子out不起作用但是ref:
void NoOp(out int value) // value must be assigned before method returns
{
}
void Increment(out int value) // value cannot be used before it has been assigned
{
value = value + 1;
}
Run Code Online (Sandbox Code Playgroud)
这些答案都没有让我满意,所以这是我的ref对比out.
我的回答是以下两页的摘要:
相比
ref/ outkeywordout或传递ref,因为属性确实是方法ref/ out不被认为是在编译时该方法签名的一部分,从而方法不能被重载如果它们之间的唯一区别是,该方法的一个需要ref的参数和其他需要一个out参数对比
ref
out
例子
不会编译,因为只有方法签名的差异是ref/ out:
public void Add(out int i) { }
public void Add(ref int i) { }
Run Code Online (Sandbox Code Playgroud)
使用ref关键字:
public void PrintNames(List<string> names)
{
int index = 0; // initialize first (#1)
foreach(string name in names)
{
IncrementIndex(ref index);
Console.WriteLine(index.ToString() + ". " + name);
}
}
public void IncrementIndex(ref int index)
{
index++; // initial value was passed in (#2)
}
Run Code Online (Sandbox Code Playgroud)
使用out关键字:
public void PrintNames(List<string> names)
{
foreach(string name in names)
{
int index; // not initialized (#1)
GetIndex(out index);
Console.WriteLine(index.ToString() + ". " + name);
}
}
public void GetIndex(out int index)
{
index = IndexHelper.GetLatestIndex(); // needs to be assigned a value (#2 & #3)
}
Run Code Online (Sandbox Code Playgroud)
作者的随机评论
out关键字的概念类似于使用ParameterDirection的Output枚举值在ADO.NET中声明输出参数ref必须使用关键字例:
public void ReassignArray(ref int[] array)
{
array = new int[10]; // now the array in the calling code
// will point to this new object
}
Run Code Online (Sandbox Code Playgroud)
有关引用类型与值类型的更多信息,请参阅传递引用类型参数(C#编程指南)
| 归档时间: |
|
| 查看次数: |
6261 次 |
| 最近记录: |