具有自定义类列表的foreach循环未打印正确的值

时间:2018-11-16 12:41:51

标签: c#

我有一个foreach循环,我试图遍历附加到类的列表

public class FInfo
{
    public string FilePath { get; set; }
    public string MD5Hash { get; set; }   
}

这是一小堂课,但我可能稍后再添加。

但是我不确定如何访问它

private void DirOut(string sDir)
    {

        try
        {
            string[] array1 = Directory.GetDirectories(sDir);
            for (int i1 = 0; i1 < array1.Length; i1++)
            {
                string d = array1[i1];
                dirC++;

                outliststring.Add(new FInfo {FilePath = d, MD5Hash = "N/A"});

                try
                {

                    String md5string; 
                    String[] array = Directory.GetFiles(d, txtFile.Text);
                    for (int i = 0; i < array.Length; i++)
                    {
                       string f = array[i];


                       outliststring.Add(new FInfo { FilePath = f, MD5Hash = "N/A" });

                    }
                }
                catch (System.Exception excpt)
                {
                    Console.WriteLine(excpt.Message);
                }
                DirOut(d);
            }
        }
        catch (System.Exception excpt)
        {
            Console.WriteLine(excpt.Message);

        }

}

此代码将项目添加到列表中。

然后我使用此代码将其写入文本文件。

 Stream fileStream2 = sfd.OpenFile();
        using (StreamWriter sw =new StreamWriter(fileStream2))
        {
            foreach (FInfo fp in outliststring)
            {
                sw.WriteLine(DateTime.Now.ToString() + ":- " + fp);


            }

            sw.Close();
            fileStream2.Close();

        }

但是,只需输入时间和日期,然后输入FInfo。有人可以解释我如何将两个值都添加到sw.writeline命令中。

谢谢

4 个答案:

答案 0 :(得分:3)

我想说最好的方法是在ToString()中覆盖FInfo

public override string ToString()
{
    return $"{FilePath}\t{MD5Hash}";
}

方法WriteLine自动在您的ToString()对象上调用fp,以将其与输出的其余字符串组合在一起。现在,您的代码仅使用在基类(很可能是ToString())上定义的object,正如您所观察到的,其默认行为是仅打印类的名称。

另一种方法是直接使用属性:

sw.WriteLine(DateTime.Now.ToString() + ":- " + $"{fp.FilePath}\t{fp.MD5Hash}" );

答案 1 :(得分:2)

就像这样使用它

foreach (FInfo fp in outliststring)
{
  sw.WriteLine(DateTime.Now.ToString() + ":- " + fp.FilePath +" "+ fp.MD5Hash );
}

答案 2 :(得分:0)

尝试在您的ToString类中覆盖FInfo方法:

public class FInfo
{
    public string FilePath { get; set; }
    public string MD5Hash { get; set; }   
    public override string ToString() => $"FilePath:{FilePath}, MD5Hash:{MD5Hash}";
}

答案 3 :(得分:0)

在C#中,有多个地方调用了对象的ToString方法,程序员无需明确声明。在您的情况下,在行sw.WriteLine(DateTime.Now.ToString() + ":- " + fp);上将调用fp.ToString();。现在,您可以按照@ rory.ap所说的那样来覆盖ToString方法,或者像这样使用字符串插值:

sw.WriteLine($"{DateTime.Now}:- {fp.FilePath}\t{fp.MD5Hash}");

编辑:字符串插值是C#中一个非常好的功能,您可以通过在引号前放置$,然后在字符串中,来告诉编译器它是插值字符串您可以使用{}(大括号)将代码放入该返回值中或者为字符串
这是一项非常强大的功能,它将替换字符串连接(现在与+一起使用)和string.Format()方法等过时的方法