类和对象

本文关键字:对象 | 更新日期: 2023-09-27 17:55:43

一个类可以有 2 个同名objects吗?如果是,则在显示时,会打印哪个特定对象的卷轴、名称和课程详细信息?

class Program
{
    static void Main(string[] args)
    {
        Student st=null;
        Console.WriteLine("Enter Records");
        for (int i = 0; i < 3; i++)
        {
            st = new Student();
            Console.WriteLine("Enter roll");
            st.roll = int.Parse(Console.ReadLine());
            Console.WriteLine("Enter name");
            st.name = Console.ReadLine();
            Console.WriteLine("Enter course");
            st.course = Console.ReadLine();
        }
        Console.WriteLine("Show Records");
        for (int i = 0; i < 3; i++)
        {
            Console.WriteLine("Roll "+st.roll.ToString());
            Console.WriteLine("Name "+st.name);
            Console.WriteLine("Course "+st.course);
        }
        Console.ReadKey();
    }
}
class Student
{
    public int roll;
    public string name;
    public string course;
}

类和对象

不,但您可以创建一个List<Students>,它基本上是一个Students列表

using System.Collections.Generic;
class Program
{
    static void Main(string[] args)
    {
        List<Student> sts = new List<Student>();
        Student st = null;
        Console.WriteLine("Enter Records");
        for (int i = 0; i < 3; i++)
        {
            st = new Student();
            Console.WriteLine("Enter roll");
            st.roll = int.Parse(Console.ReadLine());
            Console.WriteLine("Enter name");
            st.name = Console.ReadLine();
            Console.WriteLine("Enter course");
            st.course = Console.ReadLine();
            sts.Add(st);  // this is the line to be added to populate the list
        }
        Console.WriteLine("Show Records");
        for (int i = 0; i < sts.Count; i++)
        {
            st = sts[i];  // this needs to be added to read from list
            Console.WriteLine("Roll "+st.roll.ToString());
            Console.WriteLine("Name "+st.name);
            Console.WriteLine("Course "+st.course);
        }
        Console.ReadKey();
    }
}
class Student 
{
   public int roll;
   public string name;
   public string course;
}