如何将数据从streamreader获取到一个新类中



我需要通过steamreader从文本文件中读取数据,然后将该信息移动到另一个类中(我将其命名为info),最后将其移动到文本框中。我不确定我做这件事是否正确,我是新手。我得到的错误是"work2.info不包含接受2个参数的构造函数"这是我必须在中读取数据的代码

    private void openToolStripMenuItem1_Click(object sender, EventArgs e)
    {
        Stream myStream = null;
        OpenFileDialog openFileDialog1 = new OpenFileDialog();
        openFileDialog1.InitialDirectory = "c:\";
        openFileDialog1.Filter = "text files (*.txt)|*txt";
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            if ((myStream = openFileDialog1.OpenFile()) != null)
            {
                StreamReader data = new StreamReader(myStream);
               string newinfo = data.ReadLine();
              string oldinfo = data.ReadLine();
                info pepinfo = new info(newinfo, oldinfo);
               pepinfo.newinfo = textBox1.Text;
               pepinfo.oldinfo = textBox2.Text;

我想把数据放入的类是

public class info
{
    public string newinfo
    {
    }
    public string oldinfo
    {
    }
}

在您提供的代码中没有接受2个参数的构造函数
你的课可能是这样的:

public class Info
{
    public string NewInfo { get; private set; }
    public string OldInfo { get; private set; }
    public Info(string newInfo, string oldInfo)
    {
        NewInfo = newInfo;
        OldInfo = oldInfo;
    }
}

您的问题是您的类(info)没有接收oldinfo和newinfo并填充正确内容的构造函数。两个选项可更改:

private void openToolStripMenuItem1_Click(object sender, EventArgs e)
    {
        Stream myStream = null;
        OpenFileDialog openFileDialog1 = new OpenFileDialog();
        openFileDialog1.InitialDirectory = "c:\";
        openFileDialog1.Filter = "text files (*.txt)|*txt";
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            if ((myStream = openFileDialog1.OpenFile()) != null)
            {
                StreamReader data = new StreamReader(myStream);
               string newinfo = data.ReadLine();
              string oldinfo = data.ReadLine();
                info pepinfo = new info();
               pepinfo.newinfo = newinfo;
               pepinfo.oldinfo = oldinfo;

可选地,您可以更改info类以添加一个接收两个参数的构造函数,如Alex的答案。

相关内容

  • 没有找到相关文章

最新更新