C#如何构建对象列表并更改其属性

时间:2018-04-07 16:45:31

标签: c# list object

我刚刚取消了之前的整个问题以获得更基本的情况: 我想制作一个简单的加载+显示程序,例如当我加载文本文件时,文件名,文件路径和内容显示在3个不同的文本框中。

以下是代码:

using System.IO;
using System.Windows.Forms;

namespace ListBuilderTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        public class TextFile
        {
            public string TextFilePath {get;set;}
            public string TextFileTitle {get;set;}
            public string TextFileString {get;set;}
        }
        List<TextFile> TextFileList = new List<TextFile>();


        string pathToFile = "";
        private void button_Click(object sender, RoutedEventArgs e)
        {
            using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Text files|*.txt", ValidateNames = true, Multiselect = true })
            {
                if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    foreach (String file in ofd.FileNames)
                    {
                        TextFile CurrentFile = new TextFile();
                        CurrentFile.TextFilePath = ofd.SafeFileName;
                        CurrentFile.TextFileTitle = ofd.FileName;
                        if (File.Exists(pathToFile)) {

                            using (StreamReader sr = new StreamReader(pathToFile))
                            {
                                CurrentFile.TextFileString = sr.ReadLine();
                            }
                        }
                        TextFileList.Add(CurrentFile);

                        /*
                        textBox.Text = CurrentFile.TextFileTitle+"\r\n";
                        textBox_Copy.Text = CurrentFile.TextFilePath+"\r\n";
                        textBox_Copy1.Text = CurrentFile.TextFileString+"\r\n";*/
/* I would like to simplify this preceeding code into displaying it as a reference to the list rather than the current object.*/
                     }
                }
            }              
        }
    }
}

OFD有效,我可以选择多个文件,但只能获取第一个文件的属性。

我的文件是Apple.txt,Banana.txt和Cherry.txt,它们分别包含&#34; Red&#34;,&#34; Yellow&#34;和&#34;黑&#34;。

1 个答案:

答案 0 :(得分:0)

你会添加一些列表如下:

PDFList.Add(new PDFfile { PDFFileName = "name", PDFText = "text" });

你的foreach周期应该是这样的:

foreach (PDFfile file in PDFList){
    if(Regex.IsMatch(file.PDFText, "statement") == true)
    {
       file.PDFresult1 = "true";
    } 
    else
    {
       file.PDFresult1 = "false";
    }
}

其余的应该没问题