如何获取类的属性名称 [英] How to get property name of class
本文介绍了如何获取类的属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下两个课程:
I have following two classes:
public class ApplicantInfo
{
public Int32 StudentId { get; set; }
public String StudentName { get; set; }
public DateTime DateOfBirth { get; set; }
public String Phone { get; set; }
public String Email { get; set; }
public Byte[] Image { get; set; }
public SchoolDetail SchoolDetailObj { get; set; }
}
public class SchoolDetail
{
public string SchoolName { get; set; }
public string SchoolPhone { get; set; }
public string SchoolFax { get; set; }
public string SchoolEmail { get; set; }
}
在ApplicantInfo类中,我放置了SchoolDetail类的对象。
i want获取这两个类的所有属性名称。所以我写下面的代码
In ApplicantInfo class i have placed the object of SchoolDetail class .
i want to get all property names of both these classes. So i write the following code
ApplicantInfo appObj= new ApplicantInfo();
Type ApplicantInfo = appObj.GetType();
PropertyInfo[] properties = ApplicantInfo.GetProperties();
foreach (PropertyInfo property in properties)
{
var propName= property.Name.ToString()
}
获取财产ApplicantInfo的名称完美但不是SchoolDetail类的名称。它将SchoolDetailObj显示为属性。但我想获得SchoolDetail类的属性名称。请帮帮我。
It gets the property name of ApplicantInfo perfectly but not the propery names of SchoolDetail class. It shows SchoolDetailObj as the property. But i want to get the property names of SchoolDetail class . Please help me .
推荐答案
因为你使用的是ApplicantInfo类的对象。为SchoolDetail创建一个单独的对象,并在循环中迭代该属性Collection。
Because you are using the object of ApplicantInfo class. Create a separate object for the SchoolDetail and iterate that property Collection in loop.
SchoolDetailObj是ApplicantInfo类的一个属性,这意味着您正在正确地检索信息 - 但系统没有自动返回属性的属性 - 否则它将返回字符串的所有属性,字节数组,DateTime值等。
如果你想要属性的属性,你需要在该类上再次执行相同的代码作为一个单独的循环。
SchoolDetailObj is a property of the ApplicantInfo class, which means you are retrieving the info correctly - but the system doesn't automatically return the properties of properties - otherwise it would return all the properties of the string, the byte array, the DateTime value, and so on.
If you want the properties of a property, you need to execute the same code again on that class as a separate loop.
尝试下面的代码:
Try out below code :
var properties = ApplicantInfo.GetProperties().ToDictionary(x => x, x => x.GetType().GetProperties());
foreach (var item in properties)
{
Console.WriteLine(item.Key);
foreach (PropertyInfo property in item.Value)
{
Console.WriteLine(" propName = " + property.Name.ToString());
}
Console.WriteLine();
}
这篇关于如何获取类的属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文