【问题标题】:Trying to find a way to get the field names of class试图找到一种方法来获取类的字段名称
【发布时间】:2015-11-27 06:03:04
【问题描述】:

所以我希望能够得到一个类的字段

public class Person
{
    public string Id { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }
}

所以我将能够从一个类中获取公共字段名称,在这种情况下,我想要一个字符串列表为 {"Id", "Firstname", "Lastname"}

【问题讨论】:

    标签: c# class


    【解决方案1】:

    您可以使用反射来获取某个类型的属性或字段:

    var properties = typeof(Person)
                         .GetProperties()
                         .Select(p => p.Name)
                         .ToList();
    

    【讨论】:

    • 谢谢你,辛苦了
    【解决方案2】:

    反思是你的关键词。尝试类似

    typeof(Person).GetProperties();
    

    然后您可以遍历结果并获取名称。

    【讨论】:

      【解决方案3】:

      你可以利用反射。

      var propertiesInfos = typeof(Person).GetProperties(BindingFlags.Public |
                                                BindingFlags.Static);
      var propertieNames = string.Format("{{0}}",propertiesInfos.Select(prp=>prp.Name));
      

      【讨论】:

        【解决方案4】:

        你可以使用nameof(..),然后这样做:

        string nameOfField = nameof(Lastname);
        

        【讨论】:

        • 假设他正在使用 roslyn 进行编译
        猜你喜欢
        • 1970-01-01
        • 2022-06-15
        • 2017-04-18
        • 1970-01-01
        • 2019-06-11
        • 1970-01-01
        • 2016-05-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多