在c#中使用此方法时遇到问题不会清除变量



我试图将当前变量保存到列表中,然后清除变量

static void SaveInvoice(string name, string brand, double tireSize, double metalPrice, double donation, List<Customer> customerList)
{
//create object
Customer newCustomer = new Customer(name, brand, tireSize, metalPrice, donation);
customerList.Add(newCustomer);
Clear();
}
static void Clear()
{
string name = "No name";
string brand = "No name";
double metalPrice = 0;
double tireSize = 0;
double donation = 0;
}

存储后列表显示在这里

static void DisplayAllInvoices(List<Customer> customerList)
{
Console.WriteLine("nThe Right Speed Shop");
Console.WriteLine("*************************");
Console.WriteLine("n{0,-15}{1,-15}{2,-15}{3,-15}{4,-15}", "Name", "Brand", "Tire", "Metal Price", "Donation");
Console.WriteLine("{0,-15}{1,-15}{2,-15}{3,-15}{4,-15}", "********", "********", "********", "************", "********");
for (int i = 0; i < customerList.Count; i++)
{
Console.WriteLine("{0,-15}{1,-15}{2,-15}{3,-15}{4,-15}", customerList[i].Name, customerList[i].Brand, customerList[i].TireSize, customerList[i].MetalPrice, customerList[i].Donation);
}

}

Clear()方法中,您实际上创建了作用域为该方法本身的新变量。换句话说,您只需在Clear()方法的本地创建五个新变量。

同样,你不能改变值类型的值,就像函数中的double(你可以,但它不会在封闭作用域内传播)。
您可以对引用类型(如string)这样做,但这不是一个好的做法(在大多数情况下)。为什么需要清除这些值?在我看来,你不需要Clear()方法。你只要打电话给SaveInvoice的新值,你想要的任何时候,它将添加一个客户到列表(给定的customerList已定义)。

您的代码有一些问题。阅读评论:

static void SaveInvoice(string name, string brand, double tireSize, double metalPrice, double donation, List<Customer> customerList)
{
// You create newCustomer in this static method and store in the list. 
// After that, you never use newCustomer. You don't need clear
Customer newCustomer = new Customer(name, brand, tireSize, metalPrice, donation);
customerList.Add(newCustomer);
// To clear newCustomer, you need use newCustomer Clear method, not a static method
newCustomer.Clear();
}
// You must remove static to work with your instance
void Clear()
{
// Then, you can use "this" properties
this.name = "No name";
this.brand = "No name";
this.metalPrice = 0;
this.tireSize = 0;
this.donation = 0;
}

但是要小心。如果调用Clear,则清除newCustomer属性,并将该对象存储在列表中。所以你的List项会清除那些属性。我认为你只需要new和Add,而不用Clear方法。

最新更新