在运行时分配实例名称

时间:2012-12-19 09:07:32

标签: c# vb.net

我有类Student,我想创建类Student的多个实例,并希望将实例名称分配为S1,S2,S3..etc(1,2,3将为id学生,因此实例名称将在运行时作为S + StudentID)。我怎么能这样做?

感谢。

3 个答案:

答案 0 :(得分:4)

您无法在程序执行期间创建引用变量,但可以将对象引用保存到List(Of Student)Dictionary(Of String, Student)集合中。

 Dim stdList As New List(Of Student)
 stdList.Add(New Student())

或者

Dim stdMap As New Dictionary(Of String, Student)
stdMap.Add("s1", New Student())

答案 1 :(得分:1)

您可以做的一件事是在您的Student类中有一个变量,它为它们提供了唯一的名称。正如AVD所说,你仍然需要将它们存储在List或Dictionary中,但这样你就可以使用linq或select查询以你的名字找到它们,只要你设置变量。

学生班;

studentName {get;set;}

您创建的地方;

List<Student> mListStudent = new List<Student>()

For(int i = 0; i >= HoweverManyYouWantToCreate; i++)
 {
 //declare student variables
 Student student = new Student();
 studentName = i+studentID;
 mListStudent.Add(Student);
}

然后使用像LINQ这样的东西,你可以得到它;

var selectedStudent = (from students in mListStudents
                           where students.studentName == "searchParam"
                           select students).Single();

答案 2 :(得分:0)

它真的不清楚你想要什么,但这里有一个简单的例子如何生成实例名称:

List<Student> students = new List<Student>();

for(int i = 0; i < 10; i++)
{
     int id = i;
     string instanceName = String.Format("S{0}", id);
     Student s = new Student(instanceName);
     students.Add(s);
}
相关问题