是否可以使用一个方法来添加整个对象及其属性,然后在main函数中调用该方法?
我需要使用下面提供的列表提交案例3。但是,我也不想放List<Student> st = new List<Student>()
;在WriteToFile()
和AddStudent()
中都有。
例如,我有这个清单:
static void Main(string[] args)
{
List<Student> st = new List<Student>();
Student st1 = new Student(1, "Mike", "Freelancer", 9);
st1.CalculateSalary();
Student st2 = new Student(2, "Bob", "CEO", 7);
st2.CalculateSalary();
Student st3 = new Student(3, "Tina", "CEO", 3);
st3.CalculateSalary();
do
{
Console.WriteLine("============================");
Console.WriteLine("1. Write To File");
Console.WriteLine("2. Read From File");
Console.WriteLine("3. Add Student");
Console.WriteLine("============================");
answer = Convert.ToInt32(Console.ReadLine());
switch (answer)
{
case 1:
WriteToFile(filePath);
Console.WriteLine("File Created!");
break;
case 2:
ReadFromFile(filePath);
break;
case 3:
Console.WriteLine("Add Student");
break;
}
} while (answer != 4);
}
非常感谢任何帮助。
答案 0 :(得分:1)
当然,您可以创建一种方法,该方法接收学生列表,从用户收集有关新学生的信息,然后将新学生添加到列表中。它还需要确保如果传入的列表为null,那么它将初始化列表。
我猜你的一些学生属性是什么。您可以更改它们以匹配您的collect_list
类。
import
然后你可以从你的主要方法中调用它,如:
import org.apache.spark.sql.functions._
请注意,在Student
方法的开头,您永远不会将硬编码的学生添加到您的列表中。创建学生后,您可能需要添加以下内容:
/// <summary>
/// Gets student information from the user and adds a new student to the list
/// </summary>
/// <param name="existingStudents">The list of students to add to</param>
private static void AddStudent(List<Student> existingStudents)
{
// Initialize the list if it's null
if (existingStudents == null) existingStudents = new List<Student>();
int tempInt;
// Get student information from the user
Console.WriteLine("Enter new student information");
do
{
Console.Write(" 1. Enter student Id: ");
} while (!int.TryParse(Console.ReadLine(), out tempInt));
var id = tempInt;
Console.Write(" 2. Enter student Name: ");
var name = Console.ReadLine();
Console.Write(" 3. Enter student Job Title: ");
var jobTitle = Console.ReadLine();
do
{
Console.Write(" 4. Enter student years of service: ");
} while (!int.TryParse(Console.ReadLine(), out tempInt));
var yrsOfService = tempInt;
// Add the new student to the list
existingStudents.Add(new Student(id, name, jobTitle, yrsOfService));
}