【问题标题】:Using OpenFileDialog and StreamReader使用 OpenFileDialog 和 StreamReader
【发布时间】:2023-04-03 06:06:01
【问题描述】:

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

非静态字段、方法或属性需要对象引用

我之前遇到过这个错误并且能够通过它,但到目前为止我尝试过的任何事情都没有在这种情况下提供帮助。我正在发布这两个课程的代码。

第 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);
    }
}
}

第 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;
    }

}


}

【问题讨论】:

标签: c# windows winforms streamreader openfiledialog


【解决方案1】:

那是因为这不是您使用 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);
}

还有几点需要考虑:

  • 类级字段/属性应以 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();

【讨论】:

  • 感谢您在正确方向上的推动。我解决了最初的问题,但我遇到了另一个我似乎无法解决的问题(我知道这可能很容易解决)。你介意看看我发布的编辑代码吗?谢谢!
  • 是的,我完全迷路了。我不明白为什么在读取文件时没有填充数组,然后将数组作为对象发送给 Student 类。一旦数组在 Student 类中,我不应该能够访问所有元素吗?因此,例如: public string GetName() { string studentName;学生姓名=学生信息数组[0];返回学生姓名;我不是将数组中那个位置的值分配给 studentName 吗?如果是这样,那为什么我不能直接从其他类调用 GetName?
  • 好的,非常感谢您的帮助。假设用户能够选择包含某些信息的文本文件。当程序读取文件时,假设基于“,”将文本文件拆分为单独的组件。假设单独的组件填充一个数组。我需要使用数组中的信息并对数组执行操作以填充表单上的文本框/标签。我希望这能提供更多的见解。
  • @MatthewSpir​​e 您缺少的是一种将您从文件中读取的所有学生存储在内存中的方法。当我为你实现一些非常基本的东西时,看看 List
  • 文本文件中只有一个学生,一次只能打开一个文本文件。再次感谢您!
猜你喜欢
  • 2011-07-19
  • 2013-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-20
  • 2012-02-22
  • 1970-01-01
相关资源
最近更新 更多