c# - 添加已创建的对象,仅使用其名称(以字符串形式)。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 (每个人都说要避免使用),但我想不通。
解决方案
简短的回答是你不能。不适用于局部变量。但这并不意味着你不能改进你的代码来做你想做的事。
任何时候你给变量编号,你都犯了不使用容器(数组或列表)的错误。这就是你应该关注的,而不是以后如何用胶带解决这个错误。
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]);
}
推荐阅读
- sql - 从 C 程序连接到 Microsoft SQL Server
- java - 在 OkHttp 中的请求之间交换 cookie
- python - 如何使 Jupylet 应用程序在 Jupyter 笔记本的 if 语句中运行
- java - 单击按钮时未创建对话框
- reactjs - Redux-Saga 单元测试选择函数
- macos - 为什么我不能用wine打开.exe程序?
- flutter - Flutter:在某些屏幕上禁用侦听器指向事件
- pandas - 按日期和特定列的累积总和
- javascript - 如何在第一次尝试使用来自先前离子段值的 ionChange 事件时触发使用 *NgFor 的 ion-select 内部的 DOM
- java - 如何让我的扫描仪跳过“ADD_Airport”字符串?