c#使用Struct插入字段和记录



我想在使用struct创建的文件中插入一些字段和记录。我不确定我是否以正确的方式问问题,但这里是我写的代码:

 struct Student
 {
    public string Name;
    public int Age;
    public int ID;
    public string Email;
    public string Country;
    public void ClearStudentInfo()
    {
        Name = "";
        Age = 0;
        ID = 0;
        Email = "";
        Country = "";
    }
    static void Main(string[] args)
    {
        FileStream fsw = new FileStream("SomeFile.txt", FileMode.Append, FileAccess.Write);
        StreamWriter Sw = new StreamWriter(fsw);
        Sw.WriteLine("John", 22, 3254, "John123@yahoo.com", "United States");
        Sw.Close();
        fsw.Close();
    }
}

当我打开文件SomeFile.txt时,它只显示John而不显示其他记录。

有没有更有组织的插入方式?在表或文件中显示如下:

Name: John
Age: 22
ID: 3254
E-mail: John123@yahoo.com
Country: United States

如果我将插入多于学生信息,这段代码是否适用于这样做?

任何答案都将是感激的。

谢谢。

  1. 为什么要使用Struct?读过这些吗?我知道你标记了struct,但我不认为有任何理由在这里使用它

  2. StreamWriter。WriteLine并不像你想象的那样。

  3. 正如Mr Universe所提到的,您最好将输出格式设置为常规格式。但是,请参见下面的内容,以获得您想要的输出。如果你想要动态输出,你可以做一个查找表或反射。

    class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public int ID { get; set; }
        public string Email { get; set; }
        public string Country { get; set; }
        public void ClearStudentInfo()
        {
            Name = "";
            Age = 0;
            ID = 0;
            Email = "";
            Country = "";
        }
        public string FormatForOutput()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("Name: ");
            sb.Append(Name);
            sb.Append("nAge: ");
            sb.Append(Age);
            sb.Append("nID: ");
            sb.Append(ID);
            sb.Append("nE-Mail: ");
            sb.Append(Email);
            sb.Append("nCountry: ");
            sb.Append(Country);
            return sb.ToString();
        }
    }
    

    使用StringBuilder提高4+连接的效率。参考

然后你可以做

    var student = new Student() { Name = "John", Age = 22, ID = 3254, Email = "John123@yahoo.com", Country = "United StateS" };
    using (FileStream fsw = new FileStream("SomeFile.txt", FileMode.Append, FileAccess.Write))
    {
        using (StreamWriter sw = new StreamWriter(fsw))
        {
            sw.WriteLine(student.FormatForOutput());
        }
    }

using语句会为你处理流的关闭,所以你不必担心它。虽然我讨厌这个例子没有使用流,但还是看这里。

非常混淆了WriteLine参数的含义。你有这一行:

Sw.WriteLine("John", 22, 3254, "John123@yahoo.com", "United States");

不清楚为什么您认为这一行将导致您所寻求的输出,但是此调用传递字符串"John"并将作为额外参数(传递给string.Format(...))值22, 3254, "John123@yahoo.com""United States"传递给该方法。由于您不使用任何字符串替换令牌(如{0}),因此您的额外参数将被完全丢弃。

因此,您只打印出"John"也就不足为奇了。

你说你想要这样的输出:

名称:约翰。
年龄:22
ID: 3254
电子邮件:John123@yahoo.com
国家:美国

但是,当您从不输出字符串"Name:","Age:","ID:"等时,怎么可能输出它呢?

输出您想要的信息的最有组织的方法是使用CSV。

WriteLine("Name,Age,ID,E-Mail,Contry");
WriteLine("John,22,3254,John123@yahoo.com,United States");
....

它可以很容易地被程序读取,并使用Excel或类似的电子表格软件将其视为表格。

最新更新