C#默认传递参数是ByRef而不是ByVal

Nim*_*oud 20 c#

我知道默认是C#中的ByVal.我在很多地方使用了相同的变量名,然后我注意到传递的值改变了并且回来了.我想我知道C#的范围机制是错误的.此处,公共许可证会覆盖本地许可证值.我知道我可以轻松地重命名冲突中的变量名称,但我想了解有关范围的事实.

  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!
      }
  }    
Run Code Online (Sandbox Code Playgroud)

更新:我在下面添加了解决方案:

    public static void InsertLicense(License license)
    {

        license = license.Clone();
        ...
     }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 58

参数是通过值传递的 - 但参数不是对象,而是参考.该引用正在按值传递,但调用者仍将看到通过该引用对对象所做的任何更改.

这与通过引用实际传递非常不同,其中参数本身的更改如下:

 public static void InsertLicense(ref License license)
 {
    // Change to the parameter itself, not the object it refers to!
    license = null;
 }
Run Code Online (Sandbox Code Playgroud)

现在如果你打电话InsertLicense(ref foo),它会在foo之后变为空.没有参考,它就不会.

有关更多信息,请参阅我撰写的两篇文章: