C#默认情况下传递参数是ByRef而不是ByVal [英] C# Passing arguments by default is ByRef instead of ByVal
问题描述
我知道C#中的默认值为ByVal。我在许多地方使用了相同的变量名,然后我注意到传递的值会发生变化并返回。我想我知道C#的作用域机制错误。这里的公共许可证会覆盖本地的许可证值。我知道我可以轻松地在冲突中重命名变量名称,但是我想了解有关范围的事实。
I know the default is ByVal in C#. I used same variable names in many places and then I noticed passed values change and come back. I think I knew scope mechanism of C# wrong. Here public license overrides the local license values. I know I can easily rename the variable names in conflict but I would like to learn the facts about scope.
public static class LicenseWorks
{
public static void InsertLicense(License license)
{
license.registered = true;
UpdateLicense(license);
}
}
public partial class formMain : Form
{
License license;
private void btnPay_Click(object sender, EventArgs e)
{
license.registered = false;
LicenseWorks.InsertLicense(license);
bool registered = license.registered; //Returns true!
}
}
更新: ve作为解决方案添加如下:
Update: I've added below as solution:
public static void InsertLicense(License license)
{
license = license.Clone();
...
}
推荐答案
参数通过值传递-但参数不是 object ,而是 reference 。该引用正在按值传递,但通过该引用对对象所做的任何更改仍将被调用方看到。
The argument is being passed by value - but the argument isn't an object, it's a reference. That reference is being passed by value, but any changes made to the object via that reference will still be seen by the caller.
这与 real 通过引用传递非常不同,后者对参数本身进行了更改,例如:
This is very different to real pass by reference, where changes to the parameter itself such as this:
public static void InsertLicense(ref License license)
{
// Change to the parameter itself, not the object it refers to!
license = null;
}
现在,如果您调用 InsertLicense(ref foo)
,之后它将使 foo
为空。没有引用,就不会。
Now if you call InsertLicense(ref foo)
, it will make foo
null afterwards. Without the ref, it wouldn't.
有关更多信息,请参见我写的两篇文章:
For more information, see two articles I've written:
- Parameter passing in C#
- References and values (the differences between value types and reference types)
这篇关于C#默认情况下传递参数是ByRef而不是ByVal的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!