我的课如下:
class Student
{
private string name;
private string family;
private string id;
public string[] fields = {"name", "family", "id"};
public Student(string name,string family,string id)
{
this.name = name;
this.family = family;
this.id = id;
}
}
现在在另一个类中,我想遍历fields
数组中定义的成员。这是我的代码不起作用
class StudentController
{
Student student;
public StudentController(Student st)
{
this.student = st;
}
public void store()
{
foreach(string f in this.student.fields)
Console.WriteLine(this.student.f);
}
}
通常,这些任务是使用反射解决的。该反射API系统允许你检查的类型(在这种情况下,学生的实例),并询问其属性和与之相关的方法。优点是您不需要公共字段字符串数组,并且,如果添加新成员,遍历属性的代码也不会更改。缺点是使用反射会对性能产生相对的影响(但要真正担心的是,您应该始终在实际环境中进行测试)
但是您也可以实现一个简单的替代方法,以创建自己的ToString方法版本。
例如,将您的学生班级扩展为
public class Student
{
private string name;
private string family;
private string id;
public string[] fields = { "name", "family", "id", "all" };
public Student(string name, string family, string id)
{
this.name = name;
this.family = family;
this.id = id;
}
public string ToString(string field)
{
switch (field)
{
case "name":
return this.name;
case "family":
return this.family;
case "id":
return this.id;
case "all":
default:
return $"{name}, {family}, {id}";
}
}
}
现在,您可以使用
Student t = new Student("John", "McEnroe", "134");
foreach(string s in t.fields)
Console.WriteLine(t.ToString(s));
或仅用于单个字段
Console.WriteLine(t.ToString("name"));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句