C# 通过另一个更改对象值 Class

C# Change Object Value Through Another Class

我正在尝试更改其他 class 的对象值。理想情况下,我想将对象作为参数传递给 constructor/method。到目前为止,我所读到的内容是,对象在作为参数传递时充当引用,并且参数值在本地复制以用于方法的主体。所以这里有一些我测试过的配置:

案例#1。失败

class Processor 
{
   DataTable table;

   public Processor(DataTable table)
   {
       this.table = table;
   }

   public void InitializeTable()
   {
       if (table != null)
       {
           // Fill data into DataTable.
       }
   }
}

static void Main(string[] args) 
{
   DataTable mainTable = new DataTable();

   Processor processor = new Processor(mainTable);
   processor.InitializeTable();
   // mainTable still empty       
}

我认为 Processor table 持有对 mainTable 的相同引用,但在 Main 执行结束时 mainTable 仍然是空的,而 Processor table 已满。

案例#2。失败

public Processor(ref DataTable table)
{
   this.table = table;
}

我试过使用 ref 签名,但结果还是一样(mainTable 是空的)。

案例#3。失败

public void InitializeTable(DataTable table)
{
   // Fill data into table
}

我删除了构造函数并将 mainTable 提供给 InitializeTable() 方法,结果仍然相同(mainTable 为空)。

案例#4。有效!

public void InitializeTable(ref DataTable table)
{
   // Fill data into table
}

终于成功了!将 ref mainTable 输入 InitializeTable 现在可以成功填充 mainTable。这背后的解释是什么?为什么构造函数没有对 mainTable 的相同引用?为什么在将对象作为参数传递时仍然需要 ref 关键字已经意味着传递其引用?

归功于大卫:

Then that explains the behavior. You're re-assigning the local table variable to a new DataTable instance (returned by .SelectArray()). So it no longer refers to the same instance as the mainTable variable and no longer modifies that instance.