使用 OpenFileDialog 和 StreamReader

Using OpenFileDialog and StreamReader

有两个 classes,一个覆盖表单 (class 1),另一个覆盖表单上显示的内容 (class 2)。我正在尝试从 class 2 调用 class 1 中的方法以在文本框中显示某些信息。我一直收到错误消息:

An object reference is required for the non-static field, method, or property

我以前遇到过这个错误并且能够解决这个问题,但到目前为止我尝试过的任何事情都没有帮助解决这个问题。我正在发布 classes 的代码。

Class 1:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;

namespace Project6
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
        Stream myStream = null;

        //Create an instance of the open file dialog box
        OpenFileDialog ofd = new OpenFileDialog();

        //Set parameters, filter options, and filter index
        ofd.InitialDirectory = "c:\";
        ofd.Filter = "Text Files (.txt)|*.txt";
        ofd.FilterIndex = 2;

        ofd.Multiselect = false;

        if (ofd.ShowDialog() == DialogResult.OK)
        {
            try
            {
                if ((myStream = ofd.OpenFile()) != null)
                {
                    using (myStream = ofd.OpenFile())
                    {
                        StreamReader reader = new StreamReader(myStream);

                        string studentInformation = "";
                        string[] studentInformationArray = new string[11];
                        studentInformation = reader.ReadLine();

                        while ((studentInformation = reader.ReadLine()) != null)
                        {
                            studentInformationArray = studentInformation.Split(',');
                            Student newStudent = new Student(studentInformationArray);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: Could not read file from disk.  Original error: " + ex.Message);
            }
        }
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        textBox1.Text = Student.GetName(); //This generates the compiler error
        textBox1.Select(6, 5);
        MessageBox.Show(textBox1.SelectedText);
    }
}
}

Class 2:

using System;
using System.Windows.Forms;

namespace Project6
{
class Student
{
    //Initialize variables
    private string[] studentInformationArray;

    //Constructor that accepts the studentInformationArray as an argument
    public Student(string[] studentInformationArray)
    {
        this.studentInformationArray = studentInformationArray;
    }

    public Student()
    {
        string className = studentInformationArray[1];
        string semester = studentInformationArray[2];
        string picture = studentInformationArray[3];
        int project1 = Convert.ToInt32(studentInformationArray[4]);
        int project2 = Convert.ToInt32(studentInformationArray[5]);
        int project3 = Convert.ToInt32(studentInformationArray[6]);
        int project4 = Convert.ToInt32(studentInformationArray[7]);
        int project5 = Convert.ToInt32(studentInformationArray[8]);
        int project6 = Convert.ToInt32(studentInformationArray[9]);
        int midtermExam = Convert.ToInt32(studentInformationArray[10]);
        int finalExam = Convert.ToInt32(studentInformationArray[11]);
    }

    public string GetName()
    {
        string studentName;
        studentName = studentInformationArray[0];
        return studentName;
    }

}


}

那是因为这不是您使用 OpenFileDialog 的方式。看一下由 MSDN here:

托管的这个例子

编辑:回答您编辑的问题。您将始终在 Student() 构造函数中获得 NullReferenceException,因为您永远不会向 studentInformationArray 分配任何内容。所以你可以这样修复它:

public Student()
{
    studentInformationArray = new studentInformationArray[12];
    string className = studentInformationArray[1];
    // rest of your code...
}

但是,您应该考虑到 studentInformationArray 将是一个空数组,除非您给它赋值。由于您有一个采用字符串 [] 的 Student() 重载,我建议您要么删除默认构造函数,要么让它使用默认信息调用重载,如下所示:

public Student(string[] studentInformationArray)
{
     string className = studentInformationArray[1];
     // rest of your code...
     int project1 = int.Parse(studentInformationArray[4]); // always prefer int.Parse() instead of Convert.ToInt32()
     // rest of your code...
     this.studentInformationArray = studentInformationArray;
}

public Student()
{
    string[] defaultInformation = new string[12];
    // add information
    defaultInformation[0] = "some information";
    // ...
    new Student(defaultInformation);
}

还有几点需要考虑:

  • Class-level fields/properties 应该用 Pascal Case 拼写(每个单词的第一个字母大写,其余小写)
  • 尽量不要使用 this.variableName = variableName。
  • 变量名不应该包含变量的类型,那是多余的。

所以,例如,改变这个:

private string[] studentInformationArray;

为此:

private string[] StudentInformation;

回答你的最后一个问题,关于编译器错误,你需要引用 Student read 才能得到它的名字。你可以这样做:

public partial class Form1 : Form
{
    private Student StudentRead;
    // rest of your code...
    // from your read method:
    StudentRead = new Student(studentInformationArray); 

    // and finally:
    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        textBox1.Text = StudentRead.GetName();