简体   繁体   English

C#确定列表项的对象类型

[英]C# determining object type of list item

I'm trying to do a project for my C# class that adds students from either Student object(parent) or DormStudent(child) into a List that is set up for Student objects. 我正在为我的C#类做一个项目,该项目将来自Student对象(父母)或DormStudent(child)的学生添加到为Student对象设置的列表中。 I need to read in an object based on student ID and determine if its a student or dorm student and fill out the rest of the form accordingly. 我需要根据学生ID读取对象,并确定它是学生还是宿舍学生,并相应地填写其余表格。

    int pos = MainMenu.myList.FindIndex(x => x.ID == validID);
    if (MainMenu.myList[pos] == Student)
    {
        Student tempStu = MainMenu.myList[pos];
        nameTextBox.Text = tempStu.Name;
    }
    else
    {
        DormStudent tempDorm = MainMenu.myList[pos];
        dormCheckBox.Checked = true;
        dormTextBox.Text = tempDorm.Dorm;
        if (tempDorm.MealType == "B")
        {
            basicRadioButton.Checked = true;
        }
        else if (tempDorm.MealType == "M")
        {
            mediumRadioButton.Checked = true;
        }
        else
        {
            highRadioButton.Checked = true;
        }
    }

here is the list and object items 这是列表和对象项

    public static List<Student> myList = new List<Student>();

    [Serializable]
    public class DormStudent : Student
    {
        public string Dorm{get; set;}
        public string MealType { get; set; }
        public DormStudent() : base()
        {
            Dorm = "No Dorm";
            MealType = "B";
        }
        public DormStudent(int i, string n, string d, string m) : base(i, n)
        {
            Dorm = d;
            MealType = m;
        }
    }

    [Serializable]
    public class Student
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public List<int> Grades;
        public Student()
        {
            ID = 0;
            Name = "No Student";
            Grades = new List<int>();
        }
        public Student(int i, string n)
        {
            ID = i;
            Name = n;
        }
    }

To determine if an object is of a particular type, use the is operator. 要确定对象是否为特定类型,请使用is运算符。

ie. 即。

if (MainMenu.myList[pos] is Student)
{
    ...
}
else if (MainMenu.myList[pos] is DormStudent)
{
    ...
}

Now, in this particular case that won't work since the way I wrote code above will catch both types in the first clause since DormStudent inherits from Student . 现在,在这种特殊情况下,由于我上面的代码编写方式将无法正常工作,因为DormStudent继承自Student ,因此第一个子句将同时捕获这两种类型。

To handle this, reverse the checks: 要处理此问题,请反转检查:

if (MainMenu.myList[pos] is DormStudent)
{
    ...
}
else if (MainMenu.myList[pos] is Student)
{
    ...
}

This still has the problem that if any other type that inherits from DormStudent or Student comes along it will be caught by the above if-statements. 这仍然存在一个问题,即如果继承自DormStudentStudent任何其他类型出现,它将被上述if语句捕获。 If you don't want that, here's how to only identify the known types: 如果您不想这样做,请按照以下方法仅识别已知类型:

if (MainMenu.myList[pos].GetType() == typeof(DormStudent))
{
    ...
}
else if (MainMenu.myList[pos].GetType() == typeof(Student))
{
    ...
}
else
{
    ... // other type?
}

Since DormStudend is derived from student, you need to ask whether the object is a DormStudent first. 由于DormStudend源自学生,因此您需要首先询问对象是否为DormStudent。 (The usual from specific to general approach) (通常从特定到一般)

So you need to swap your If-Statement like this: 因此,您需要像这样交换If-Statement:

if(MainMenu.myList[pos] is DormStudent)
{
  ...
}
else
{
   ...
}

Reply to your comment: You can use the as keyword instead to make it abit easier. 回复您的评论:您可以改用as关键字来使其变得更容易。 as is basically a 'try cast' It will return the casted object or null if it cannot cast. 基本上是一个“尝试转换”,它将返回已转换的对象;如果无法转换,则返回null。

Student student = MainMenu.myList[pos];
DormStudent dormStudent = student as DormStudent;

if(dormStudent!= null)
{
     dormTextBox.Text = dormStudent.Dorm;
}
else
{
    nameTextBox.Text = student.Name;
}

I leave the comments on whether this design is optimal to others, but what you're looking for is the is operator keyword. 对于这种设计是否对其他人最佳,我留下评论,但是您正在寻找的是is运算符关键字。

var someStudent = MainMenu.myList[pos];
//Check for null here
if (someStudent is DormStudent )
{
    DormStudent tempDorm = someStudent as DormStudent ;
    dormCheckBox.Checked = true;
    dormTextBox.Text = tempDorm.Dorm;
    if (tempDorm.MealType == "B")
    {
        basicRadioButton.Checked = true;
    }
    else if (tempDorm.MealType == "M")
    {
        mediumRadioButton.Checked = true;
    }
    else
    {
        highRadioButton.Checked = true;
    }
    Student tempStu = someStudent ;
    nameTextBox.Text = tempStu.Name;
}
else
{
    nameTextBox.Text = someStudent.Name;
}

But you can also you as with a null check: 但是您也可以as其作为null检查:

var someStudent = MainMenu.myList[pos];
//Null check here?
var dormStudent = someStudent as DormStudent;
if (dormStudent != null)
{
    DormStudent tempDorm = someStudent as DormStudent ;
    dormCheckBox.Checked = true;
    dormTextBox.Text = dormStudent.Dorm;
    if (dormStudent.MealType == "B")
    {
        basicRadioButton.Checked = true;
    }
    else if (dormStudent.MealType == "M")
    {
        mediumRadioButton.Checked = true;
    }
    else
    {
        highRadioButton.Checked = true;
    }
}
nameTextBox.Text = someStudent.Name;

if (!(MainMenu.myList[pos] is DormStudent)) 如果(!(MainMenu.myList [pos]是DormStudent))

you need is operator to test the type and test for descendant. 您需要的操作员来测试类型并测试后代。 You can as well retrive Student from the list and cast it to DormStudent using as operator and check if null. 您也可以从列表中检索Student,然后使用as运算符将其转换为DormStudent并检查是否为null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM