如何获取类的PropertyName?
例如,如何获取 Student 类实例的 PropertyName“StudentName”。
public class Student
{
public string StudentName{get;set;}
}
Student student = new Student();
//I want to get the PropertyName "StudentName"
student.StudentName.GetName();
要获取属性的实际名称,只需访问类,您可以使用以下命令:
Type studentType = typeof(Student);
PropertyInfo[] AllStudentProperties = studentType.GetProperties();
如果您知道要查找的名称并且只需要访问属性本身,请使用:
Type studentType = typeof(Student);
PropertyInfo StudentProperties = studentType.GetProperty("StudentName");
获得 PropertyInfo
后,只需使用 PropertyInfo.Name
,它将给出字符串表示形式。
如果在此之后您不想要该值,您将必须有一个实例化的类来获取该值。除此之外,如果您使用 static
属性,则可以在不实例化的情况下提取值。