gpt4 book ai didi

c# - 方法参数的 ref、val 和 out 是什么意思?

转载 作者:IT王子 更新时间:2023-10-29 04:29:56 25 4
gpt4 key购买 nike

我正在寻找一个清晰、简明和准确的答案。

理想情况下作为实际答案,尽管欢迎链接到好的解释。

这也适用于 VB.Net,但关键字不同 - ByRefByVal

最佳答案

默认情况下(在 C# 中),将对象传递给函数实际上传递的是对该对象的引用副本。更改参数本身只会更改参数中的值,而不会更改指定的变量。

void Test1(string param)
{
param = "new value";
}

string s1 = "initial value";
Test1(s1);
// s1 == "initial value"

使用outref 传递对函数调用中指定变量的引用。对 outref 参数值的任何更改都将传递回调用方。

outref 行为相同,除了一个细微差别:ref 参数需要在调用前初始化,而 out 参数可以取消初始化。通过扩展,ref 参数保证在方法开始时被初始化,而 out 参数被视为未初始化。

void Test2(ref string param)
{
param = "new value";
}

void Test3(out string param)
{
// Use of param here will not compile
param = "another value";
}

string s2 = "initial value";
string s3;
Test2(ref s2);
// s2 == "new value"
// Test2(ref s3); // Passing ref s3 will not compile
Test3(out s2);
// s2 == "another value"
Test3(out s3);
// s3 == "another value"

编辑:作为dp指出,outref 之间的区别仅由 C# 编译器强制执行,而不是由 CLR 强制执行。据我所知,VB 没有 out 的等效项,仅实现 ref(作为 ByRef),匹配 CLR 的支持。

关于c# - 方法参数的 ref、val 和 out 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13060/

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