【发布时间】:2021-10-08 22:44:08
【问题描述】:
我试图重现书中的一个代码示例,其中程序计算提供的数字的平方,在 cmd 中显示结果,并将结果记录在 txt.file 中。对于提供的数字 1、2、3、4,程序可以计算结果并在 cmd 中显示为:
1
4
9
16
但是,当它需要在txt文件中记录结果时,它只记录16。我不确定它是否覆盖了以前的数据或只记录最后一个平方数。我想提示一下这里出了什么问题以及如何修复它以便能够记录所有结果,就像在 cmd 中一样。
using System;
using System.IO;
using System.Collections.Generic;
namespace Chapter4Practice
{
public interface ITransformer
{
int Transform(int x);
}
public class Util
{
public static void TransformAll(int[] values, ITransformer t)
{
for (int i = 0; i < values.Length; i++)
values[i] = t.Transform(values[i]);
}
}
public class Squarer : ITransformer
{
public int Transform(int x) => x * x;
}
class Test
{
static void Main()
{
int[] values = { 1, 2, 3, 4 };
Util.TransformAll(values, new Squarer());
foreach (int i in values)
{
Console.WriteLine(i);
WriteProgressToFile(i.ToString());
}
}
static void WriteProgressToFile(string i) => System.IO.File.WriteAllText("progress.txt", i.ToString()+ Environment.NewLine);
}
}
【问题讨论】:
标签: c#