c# - 如何获取类的PropertyName?

标签 c#

<分区>

如何获取类的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 属性,则可以在不实例化的情况下提取值。

关于c# - 如何获取类的PropertyName?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2680646/

相关文章:

C# : The best solution to parse the xml file?

c# - Winform/usercontrols - 属性为空时使用的异常类型

c# - 是否有一种已知的快速算法来查找与给定数字相乘的所有数字对?

c# - 我想在具有管理员权限的有限帐户中运行我的功能

C# 如何使重复输入重叠?

c# - 微软语音识别平台

c# - 404 未找到 Ajax jquery MVC

c# - 底层连接已用linkedin关闭

c# - 尝试按选定行遍历 DataGridView;接收索引越界

c# - 根据地区验证日期