How to get the PropertyName of a class? [duplicate]
How to get the PropertyName of a class?
For example, How can I get the PropertyName "Student开发者_开发百科Name" of a Student class instance.
public class Student
{
public string StudentName{get;set;}
}
Student student = new Student();
//I want to get the PropertyName "StudentName"
student.StudentName.GetName();
To get the actual name of the property, just from having access to the class, you can use the following:
Type studentType = typeof(Student);
PropertyInfo[] AllStudentProperties = studentType.GetProperties();
If you know the name you're looking for and just need access to the property itself, use:
Type studentType = typeof(Student);
PropertyInfo StudentProperties = studentType.GetProperty("StudentName");
Once you have the PropertyInfo
, simply use PropertyInfo.Name
, which will give the string representation.
If after this you wan't the value, you're going to have to have an instantiated class to get the value. Other than this, if you use a static
property, you can pull the value without instantiating it.
Updated answer:
C# now has a nameof
operator, so you should use that.
You can use it on the instance or the Student type itself.
Example:
nameof(student.StudentName); // returns "StudentName"
nameof(Student.StudentName); // returns "StudentName"
Original answer (written before nameof
existed):
You can use the following static method:
static string GetName<T>(T item) where T : class
{
var properties = typeof(T).GetProperties();
return properties[0].Name;
}
Use like so:
string name = GetName(new { student.StudentName });
See this question for details.
精彩评论