在C#程序中,我已经建立了一种从列表中删除对象的方法。用户输入要删除的项目的索引,然后要求用户确认删除,如果用户确认,则从列表中删除该项目,否则列表保持不变。我不确定将参数传递给方法的最佳方法。我尝试通过引用传递列表(作为out
参数):
static void DeleteCustomer(out List<Customer> customers)
{
// ...display list of objects for user to choose from...
int deleteId = ReadInt("Enter ID of customer to delete: ");
Console.Write("Are you sure you want to delete this customer?");
if (Console.ReadLine().ToLower() == "y")
{
customers.RemoveAt(deleteId);
}
}
上面的代码无法正常工作,因为出现错误使用未分配的局部变量'customers'和在控制离开当前方法之前必须将out参数'customers'分配给] >>。我当时想我可以按值传递列表并返回相同的列表,如下所示:
static List<Customer> DeleteCustomer(List<Customer> customers) { int deleteId = ReadInt("Enter ID of customer to delete: "); Console.Write("Are you sure you want to delete this customer?"); if (Console.ReadLine().ToLower() == "y") { customers.RemoveAt(deleteId); } return customers; } // ...which would be called from another method with: List<Customer> customers = DeleteCustomer(customers);
但是这似乎效率不高,因为同一变量按值传递然后返回。
在这种情况下传递参数的最有效方法是什么?
在C#程序中,我已经建立了一种从列表中删除对象的方法。用户输入要删除的项目的索引,然后要求用户确认删除,然后从...
List
像所有引用类型一样,作为reference