【发布时间】:2021-10-07 21:57:09
【问题描述】:
似乎任何 C# 问题都必须重复,但我找不到。
用 C# 编码:
MyClassType mt = null;
dofunction(mt);
// mt was modified in dofunction to some non null value, but comes back still null
dofunction 类似于
public void dofunction(MyClassType mt){
mt="xxxxx";
}
要在调用者中看到更新,我必须使用 ref 关键字。为什么?我认为类实例总是作为 ref 传递,而不需要 ref 关键字。 MyClassType 告诉 dofunction mt 是一个类实例,但它的行为不像它。我猜设置 mt=null 不是类实例,但那又怎样?
同样,问题是“为什么?”。
我已经编辑了............
改写问题,这似乎与所谓的重复问题不同: 如果您在调用之前将 mt 设置为 null,则表示您没有使用 ref 关键字。如果您在调用之前将 mt 设置为 new MyClassType(),则它就像您使用了 ref 关键字一样。为什么 C# 会以这种令人费解的方式行事?
这是演示我的前提的示例代码。我正在使用 Visual Studio 2019、ASP.Net Core 5 编写 C#。
这里是调用例程:
public IActionResult RefTest() {
MrShow m1 = null; // in this case doFunction acts as if m1 does NOT have the ref keyword
MyProject.Utils.TestIt.doFunction(m1);
string m1contents = "result when m1 set to null: ";
if (m1 == null) m1contents += "null / ";
else m1contents += m1.idnmbr + " / ";
m1contents += "result when m1 set to class instance: ";
m1 = new MrShow(); // in this case doFunction acts as if m1 does have the ref keyword
MyProject.Utils.TestIt.doFunction(m1);
if (m1 == null) m1contents += "null / ";
else m1contents += m1.idnmbr + " / ";
ViewBag.m1contents = m1contents;
return View();
}
这就是所谓的:
static internal void doFunction(MrShow m1) {
if (m1 != null) {
m1.idnmbr = "doFunction changed this";
}
else {
m1 = new MrShow();
m1.idnmbr = "m1 did not change this";
}
}
在我的网络应用中,我得到了结果:
RefTest Results
result when m1 set to null: null / result when m1 set to class instance: doFunction changed this /
【问题讨论】:
-
在 C# 中,参数可以通过值或引用传递给参数。即使参数是引用类型,参数也是按值传递的。
-
@GSerg - 是的,这是一个重复的问题。但我喜欢the answer "walking with the dog" Caius Jard 给出的。 ;-)
-
如果您在调用之前将 mt 设置为 null,就好像您没有使用 ref 关键字 - 这就像您没有使用
ref关键字,因为您没有使用 ref 关键字。 如果你在调用之前将 mt 设置为 new MyClassType(),它就像你使用了 ref 关键字一样 - 不,它没有 -
Grrrrrrrrrrrr。 “不,它没有”????????
标签: c# parameter-passing ref