Skip to main content
 首页 » 编程设计

c#之操纵引用对象

2024年02月24日15dudu

有没有一种方法可以传递对对象的引用,在我的方法中操作它,从而直接更改引用的对象?

例如,我想将一个下拉列表传递到我的方法中,对其进行操作并完成。此方法将接受任何下拉列表:

public static void MyMethod(Dropdownlist list1, ref DropdownList list2) 
{ 
    // just manipulate the dropdown here... no need to returnit.  Just Add or remove some values from the list2 
} 

显然我不能只将下拉列表对象传递给 list2。那我该怎么做呢?我将删除列表中的一些值。这将是一个很好的实用方法,因此我不必为了我将要在该方法中执行的功能而到处重复此代码。

请您参考如下方法:

如果您在单个引用类型上操作内部数据,那么您不需要在方法签名上做任何特殊的事情。将引用类型的对象传递给方法时,您不会传递副本。相反,您传递了对该对象的引用。操纵此引用将更改原始对象。

void MyMethod(List<string> list) { 
  list.Add("foo"); 
} 
 
void Example() { 
  List<string> l = new List<sting>(); 
  MyMethod(l); 
  Console.WriteLine(l.Count);  // Prints 1 
  MyMethod(l); 
  Console.WriteLine(l.Count);  // Prints 2 
} 

现在,如果您想更改原始引用指向的位置,您将需要一个 ref 修饰符。