EndOfStream不能像方法一样使用

时间:2016-04-13 00:56:41

标签: c# list class methods

我必须为我的课程创建一个程序,我差不多完成了。我将此代码链接到名为PersonEntry的类。我试图找出为什么我的EndOfStream无法正常工作。它说它不能用作方法

namespace Jason_Todd___IS_204___HW11CH9_7
{
    public partial class Form1 : Form
    {
        string selectedName = "";
        List<PersonEntry> nameList = new List<PersonEntry>();

    public Form1()
        {
            InitializeComponent();
        }

        // gotta load the names from this list. Because, you know, I need to get a grade.
    private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                StreamReader inputFile;
                inputFile = File.OpenText("Personlist.txt");

                string inRecord;

                while (!inputFile.EndOfStream())  // This is where my error occurs.
                {
                    inRecord = inputFile.ReadLine();
                    string[] tokens = inRecord.Split(',');

                    PersonEntry friendObj = new PersonEntry(tokens[0],tokens[1],tokens[2]);

                    listBox1.Items.Add(friendObj.Name);


                    nameList.Add(friendObj);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                MessageBox.Show("Exception in try/catch. ");
            }
        }

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            selectedName = listBox1.SelectedItem.ToString();
            PersonInfoForm myPerInfoForm = new PersonInfoForm();
            Label label1 = new Label();
            label1.Size = new Size(270, 75);
            label1.Location = new Point(10, 10);

            foreach (PersonEntry PersonEntry in nameList)
            {
                if (PersonEntry.Name == selectedName)
                {
                    label1.Text += "Name: " + PersonEntry.Name + "\n" +
                                   "Email: " + PersonEntry.Email + "\n" +
                                   "Phone number: " + PersonEntry.PhoneNum;
                }
            }

            myPerInfoForm.Controls.Add(label1);
            myPerInfoForm.ShowDialog();
        }

        private void exitButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}

2 个答案:

答案 0 :(得分:1)

  

.EndOfStreamStreamReader类的只读属性。得到一个   指示当前流位置是否在结尾的值   流。

因此不需要()来访问属性的值。声明如下:

 while (!inputFile.EndOfStream)  // This line will not show error now
 {
     // your stuff here       
 }

答案 1 :(得分:0)

抱歉,我无法回复其他人的评论,所以我在这里回答你的ListBox问题。

ListBoxes保存对象而不是字符串。将项目添加到listBox时执行此listBox1.Items.Add(friendObj);

然后你有两个选择。

1)设置listBox1.DisplayMember = "Name"

2)在您的Friend类中重写ToString()方法并使其返回如下名称

public override ToString()
{
    return this.Name;
}

默认情况下,ListBoxes会对添加到它们的对象调用ToString(),以确定要在UI中显示的文本,除非您明确设置ListBox的DisplayMember属性。