C#为每个循环调用所有属性 [英] C# calling all properties, for each loop
问题描述
我有一个foreach循环,我想在foreach循环中调用某个类的所有属性,这样我就不必全部写出来.
I have a foreach loop and I would like to call all properties of a certain class in the foreach loops so I don't have to write it all out.
我创建的课程
public Person()
{
firstname = "";
surname = "";
haircolor = "";
eyecolor = "";
weight = 0;
height = 0;
age = 0;
}
这是我要压缩的代码
Console.WriteLine("Please enter the next persons firstname");//new person user input (firstname)
addperson.firstname = Console.ReadLine();
Console.WriteLine("Enter the persons surname");//surname
addperson.surname = Console.ReadLine();
Console.WriteLine("Enter " + addperson.name + "'s hair color");//hair color
addperson.haircolor = Console.ReadLine();
Console.WriteLine("Enter the age of " + addperson.firstname);//age
addperson.age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the weight of " + addperson.firstname);//weight
addperson.weight = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter the height of " + addperson.firstname);//height
addperson.height = Convert.ToDouble(Console.ReadLine());
我已经开始了foreach循环,我想一种将所有代码压缩为循环的方法
I have started on the foreach loop, I would like a way to compact all of that code to a loop
foreach (Person.)
{
Console.WriteLine("Please enter " +addperson.ToString);
Person.addperson = Console.ReadLine();
}
任何帮助将不胜感激
推荐答案
您需要使用反射功能才能动态地遍历每个属性,我个人不会将其更改为使用反射功能,因为反射功能会降低性能,但这是代码供您参考:
you need to use reflection to be able to loop over each property dynamically, personally i wont change it to use reflection since reflection has performance penalties, but here is the code for your reference:
将类别"字段更改为属性:
Change Class fields to properties:
public class Person
{
public string firstname {get;set;}
public string surname {get;set;}
public string haircolor {get;set;}
public string eyecolor {get;set;}
public string weight {get;set;}
public string height {get;set;}
public string age {get;set;}
}
在您的主要方法中编写以下代码:
Write this code in your main method:
Person addperson = new Person();
PropertyInfo[] props = addperson.GetType().GetProperties();
foreach(PropertyInfo prop in props)
{
Console.WriteLine("Please enter " + prop.Name.ToString());
string input = Console.ReadLine();
prop.SetValue(addperson, input, null);
}
这行代码:
PropertyInfo[] props = addperson.GetType().GetProperties();
返回Person类型(类)的所有公共属性,然后每个PropertyInfo对象发现该属性的属性并提供对其元数据的访问.
Returns all the public properties of the Person type (class), then each PropertyInfo object discovers the attributes of the property and provides access to its metadata.
这篇关于C#为每个循环调用所有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!