Rub*_*922 6 c# methods pass-by-reference pass-by-value argument-passing
在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);
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码不起作用,因为我得到错误使用未分配的本地变量'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);
Run Code Online (Sandbox Code Playgroud)
但这似乎并不高效,因为相同的变量按值传递然后返回.
在这种情况下传递参数的最有效方法是什么?
List与所有引用类型一样,它作为对象的引用传递,而不是对象的副本。
请注意,这与通过引用传递有很大不同,因为这意味着参数的分配会传播到调用者,但事实并非如此
它确实意味着对对象的修改(例如由 执行的修改RemoveAt)将自动传播到调用者。
因此,只要通过即可;不需要返回值或out/ref参数。
您很少将out/ref用于引用类型,并且当用于值类型时,与返回相比,性能差异非常小,因此您不必担心它,除非您已经分析并确保问题发生在那里。使用最惯用的方式。