我正在使用GUI作为客户端进行WCF服务,但是我在打印添加的当前项目列表时遇到问题。我有一个代码可以在列表中添加新条目:
public bool Add_Data(Data sample)
{
container.Add(sample);
Console.WriteLine("New record added!");
return true;
}
并且它正在工作,但是当我尝试查看添加的记录时,首先尝试它是否有效,但是如果我想再次查看它,则列表添加相同的元素。告诉你它是如何工作的:
这是我的“显示记录”代码:
public string Show_Data()
{
Console.WriteLine("Printing records");
foreach (Data record in container)
{
string final_result = ("\nID: "+ + record.ID + " " + "product: " + record.product + " " + "category: " + record.category + " " + "price: " + record.price + " " + "quantity: " + record.quantity + " " + "\n ");
result += final_result;
}
return result;
}
如果你知道如何解决它,请告诉我。
答案 0 :(得分:0)
您需要研究变量范围。您在Show_Data()
方法之外声明了结果。每次调用该方法时,您都在执行result += final_result;
,这会添加到结果中。尝试下面的代码,你会得到不同的结果。
public string Show_Data()
{
Console.WriteLine("Printing records");
var output = string.Empty;
foreach (Data record in container)
{
string final_result = ("\nID: "+ + record.ID + " " + "product: " + record.product + " " + "category: " + record.category + " " + "price: " + record.price + " " + "quantity: " + record.quantity + " " + "\n ");
output += final_result;
}
return output;
}
另外,我会考虑使用字符串构建器和字符串格式。
public string Show_Data()
{
Console.WriteLine("Printing records");
var output = new StringBuilder();
foreach (Data record in container)
{
string final_result = string.Format("ID: {0} product: {1} category: {2} price: {3} quantity: {4}", record.ID, record.product, record.category, record.price, record.quantity);
// if using C# 6
// string final_result = string.Format($"ID: {record.ID} product: {record.product} category: {record.category} price: {record.price} quantity: {record.quantity)}";
output.AppendLine(final_result);
}
return output.ToString();
}