我被要求创建一些结构:学生、教师、类(class)、项目 然后制作一个数组来保存 5 个学生结构,并为数组中学生的字段赋值,我一直在创建数组来保存结构,这里是代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Module4Assignment
{
class Program
{
//Student structure:
public struct Student
{
public Student (string name , string address , string country , string birthday , int telephone)
{
this.Name = name;
this.Address = address;
this.Country = country;
this.Birthday = birthday;
this.Telephone =telephone;
}
public string Name;
public string Address;
public string Country;
public string Birthday;
public int Telephone;
}
//Teacher structure:
public struct Teacher
{
public Teacher(string tname, string taddress, string tcountry, string tbirthday, int ttelephone)
{
this.TName = tname;
this.TAddress = taddress;
this.TCountry = tcountry;
this.TBirthday = tbirthday;
this.TTelephone = ttelephone;
}
public string TName;
public string TAddress;
public string TCountry;
public string TBirthday;
public int TTelephone;
}
//Program structure
public struct Program
{
public Program(string pname , string department , int pcredits)
{
this.PName = pname;
this.Department = department;
this.PCredits = pcredits;
}
public string PName;
public string Department;
public int PCredits;
}
//Course structure
public struct Course
{
public Course(string cname, string day, int ccredits)
{
this.CName = cname;
this.Day = day;
this.CCredits = ccredits;
}
public string CName;
public string Day;
public int CCredits;
}
static void Main(string[] args)
{
//Instantiating 5 students structures:
Student student1 = new Student();
Student student2 = new Student();
Student student3 = new Student();
Student student4 = new Student();
Student student5 = new Student();
//creating the array:
string[] studentArray = new string[5];
studentArray[0]=student1;
studentArray[1]=student2;
studentArray[2]=student3;
studentArray[3]=student4;
studentArray[4]=student5;
}
}
}
最佳答案
我对您在这里所做的事情有很多疑问,但简单的答案是您不能将 Student 对象放入字符串数组中:
static void Main(string[] args)
{
//Instantiating 5 students structures :
Student student1 = new Student();
Student student2 = new Student();
Student student3 = new Student();
Student student4 = new Student();
Student student5 = new Student();
//creating the array :
Student [] studentArray = new Student[5]; // <---- array of Student!
studentArray[0]=student1;
studentArray[1]=student2;
studentArray[2]=student3;
studentArray[3]=student4;
studentArray[4]=student5;
}
关于c# - 如何创建一个数组来保存结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29630272/