C#,使用变量作为新对象的名称 [英] C#, using variable for name of new object
本文介绍了C#,使用变量作为新对象的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApp1
{
public class Student
{
public static int Count = 0;
public int ID { get; set; }
public string Name { get; set; }
Dictionary<int, Student> students = new Dictionary<int, Student>();
public Student (string name, int id)
{
Name = name;
ID = id;
}
public static void addStudent()
{
Student.Count++; // incrementing value for new student id.
Console.Write("Please enter student's name: "); // grabbing input from user.
string studentName = Console.ReadLine();
Console.WriteLine("Student ID value: {0}", Student.Count); // for testing.
int studentID = Student.Count;
/* Student (studentName) = new Student (studentName, studentID) -- The issue is with this line*/
Student added = new Student(studentName, studentID) // using this as a temp for now.
{
Name = studentName,
ID = studentID
};
}
}
}
我尝试过的事情:
我觉得我已经尝试了一切。
我想使用变量的原因是因为学生将从Main的菜单中添加。
使用静态变量Count(在此类中)作为对象名称可能更有意义。
无论我还是需要使用变量。
非常感谢任何帮助。
What I have tried:
I feel like I've tried everything.
The reason I want to use a variable is because students will be getting added from a menu in Main.
It would probably make more sense to use the static variable Count (in this class) for the name of the object.
Regardless I would still need to use a variable.
Any help is greatly appreciated.
推荐答案
我不知道你在说什么,变量?您似乎已经使用一个来设置新Student对象的Name属性,但我不确定。当你说对象的名字时,我并不完全确定你指的是什么。
我认为你是什么寻找的是:
I have no idea what you're talking about, "variable"? It appears you're already using one to set the Name property of a new Student object, but I'm not sure. I'm not entirely sure what you're referring to when you say "name of object".
I think what you're looking for is this:
Student added = new Student(studentName, studentID);
或
or
Student added = new Student()
{
Name = studentName,
ID = studentID
};
我不明白为什么你需要一个变量...
如果您需要添加学生并根据学生姓名检索它,您可以使用字典。
i don't understand why you need a variable ...
if you need add student and retrieve it based on the student name you can do it with dictionary.
ictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("student1", 1);
dict.Add("student2", 2);
dict.Add("student3", 3);
dict.Add("student4", 4);
并且可以根据关键
and can search students based on key
dict.ContainsKey("student1")
并根据键(学生姓名)提取值
and extract values based on the key (which is student name)
dict["student1"].ToString ());
i认为它可能对你有用...
i think it may work for you...
这篇关于C#,使用变量作为新对象的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文