【问题标题】:How to get the PropertyName of a class? [duplicate]如何获取一个类的PropertyName? [重复]
【发布时间】:2011-02-10 11:01:42
【问题描述】:

如何获取一个类的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(); 

【问题讨论】:

标签: c#


【解决方案1】:

要获取属性的实际名称,只需访问类,您可以使用以下内容:

Type studentType = typeof(Student);
PropertyInfo[] AllStudentProperties = studentType.GetProperties();

如果您知道要查找的名称并且只需要访问属性本身,请使用:

Type studentType = typeof(Student);
PropertyInfo StudentProperties = studentType.GetProperty("StudentName");

获得PropertyInfo 后,只需使用PropertyInfo.Name,它将给出字符串表示形式。

如果在此之后您不需要该值,您将必须有一个实例化的类来获取该值。除此之外,如果您使用 static 属性,您可以在不实例化的情况下提取该值。

【讨论】:

    【解决方案2】:

    更新答案:

    C# 现在有一个nameof 运算符,所以你应该使用它。

    您可以在实例或 Student 类型本身上使用它。

    例子:

    nameof(student.StudentName); // returns "StudentName"
    nameof(Student.StudentName); // returns "StudentName"
    

    原始答案(写在nameof 存在之前):

    您可以使用以下静态方法:

    static string GetName<T>(T item) where T : class
    {
        var properties = typeof(T).GetProperties();
        return properties[0].Name;
    }
    

    这样使用:

    string name = GetName(new { student.StudentName });
    

    详情请见this question

    【讨论】:

      猜你喜欢
      • 2011-05-17
      • 1970-01-01
      • 1970-01-01
      • 2012-03-18
      • 2017-03-06
      • 1970-01-01
      • 2018-11-27
      • 2013-07-15
      • 2019-04-19
      相关资源
      最近更新 更多