开发者

How to get the PropertyName of a class? [duplicate]

This question already has answers here: Workaround for lack of 'nameof' operator in C# for type-safe databinding? (8 answers) Closed 8 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜