首页 > 解决方案 > 添加已创建的对象,仅使用其名称(以字符串形式)。C#

问题描述

我知道这可能永远不会在现实生活中使用,但是说我有一堆从 Student 类实例化的名称对象。即我知道我的学生对象的名称是“s1,s2,s3”,我想将它们添加到学生列表中(使用循环),而不是他们的字段,而是对象本身。再次,我想强调的是,一般来说这样做是没有意义的,当然容器会更好。我知道这是完全不正确的语法,但我试图捕捉的想法是:

Student s1 = new Student(3434,"John Smith");
Student s2 = new Student(5454, "Sam Wilkies");
Student s3 = new Student(7878, "Jim Jam");
List<Student> students= new List<Student>();
for(int i; i<=3; i++){
    string j= "s" + i.ToString();
    students.add(Student[j]);

就像我说的,我知道这是完全不正确的语法。我想也许我可以使用 Activator.CreateInstance (每个人都说要避免使用),但我想不通。

标签: c#listclassoop

解决方案


简短的回答是你不能。不适用于局部变量。但这并不意味着你不能改进你的代码来做你想做的事。

任何时候你给变量编号,你都犯了不使用容器(数组或列表)的错误。这就是你应该关注的,而不是以后如何用胶带解决这个错误。

Student[] s = new[] {
    new Student(3434,"John Smith"),
    new Student(5454, "Sam Wilkies"),
    new Student(7878, "Jim Jam")
}

// matter of fact this is not needed now, just to show you the loop:
List<Student> students = new List<Student>();

for(int i = 0; i < 3; i++)
{
    students.Add(s[j]);
}

推荐阅读