如何解决计算器历史:添加到数组
我需要为我正在用 C# 开发的计算器创建一个计算器历史记录。
从 OperateBLL.cs 中,我将对象和运算符/结果传递给 HistoryDAL.cs 中名为 WriteHistory 的方法,从这里我使用 SteamWriter 连接到文本文件,调用 history.txt。
我想做的是将每个操作添加到列表中,然后继续将列表的每个元素保存到文本文件中,该文件将在 Form1.cs 中调用并显示在 TextBox tb_operations 中。
我目前要做的就是继续覆盖列表索引 0 处的相同条目,我不确定如何继续将每组操作添加到数组并继续将它们写入文本文件。
History.Dal.cs
public void writeHistory(CalculovO yeah,string operator,double resul)
{
StreamWriter escribir = new StreamWriter("history.txt");
List<string> history = new List<string>();
history.Add(yeah.Num2.ToString() + " " + operador + " " + yeah.Num1.ToString() + " = " + result);
foreach (var entry in history) {
escribir.WriteLine(entry);
}
escribir.Close();
}
OperarBLL.cs(我把这里的参数传给HistoryDAL.cs中的方法)
controladorDAL.writeHistory(sumaObjeto,"*",resultado);
Form1.cs(它可以很好地写入文本框)
private void readHistory()
{
string path = "historial.txt";
string[] readHist = File.ReadAllLines(path);
foreach (string s in readHist)
{
tb_historial.Text = s;
}
}
解决方法
每次调用 writeHistory
时都会在行中创建新列表:
List<string> history = new List<string>();
history
必须在 writeHistory
之外定义/创建。它可以定义为包含方法 writeHistory
的类中的字段,然后您将可以从该方法访问该字段。
public class A
{
List<string> history = new List<string>();
public void writeHistory(CalculoVO yeah,string Operator,double result)
{
StreamWriter escribir = new StreamWriter("history.txt",true);
history.Add(yeah.Num2.ToString() + " " + Operator + " " + eah.Num1.ToString() + " = " + result);
// ....
}
}
另一种可能是在另一个对象中创建 history
并将其作为参数传递给 writeHistory
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。