首页 > 解决方案 > 如何在 C# 中获取对象属性名称和值的列表?

问题描述

假设我有一个简单的课程

public class Person {
    string firstName;
    string lastName;
    int age;
    .... additional properties
}

然后我有一些代码确实说

person = new Person("bob", "Smith", 27);

有没有办法(也许使用 Linq?)我可以得到一个返回的字符串

“名字鲍勃/n姓史密斯/n年龄27”

标签: c#stringlinq

解决方案


是的,试试这个:

void Main()
{
    var person = new Person("bob", "Smith", 27);

    var result = String.Join(Environment.NewLine, typeof(Person).GetFields().Select(p => $"{p.Name} {p.GetValue(person)}"));

    Console.WriteLine(result);
}

public class Person
{
    public Person(string firstName, string lastName, int age)
    {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }
    public string firstName;
    public string lastName;
    public int age;
}

这给出了:

名字鲍勃
姓史密斯
27 岁

如果您可以控制Person该类,那么这是解决此问题的更惯用的方法:

void Main()
{
    var person = new Person("bob", "Smith", 27);

    var result = person.ToString();

    Console.WriteLine(result);
}

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }

    public Person(string firstName, string lastName, int age)
    {
        this.FirstName = firstName;
        this.LastName = lastName;
        this.Age = age;
    }

    public override string ToString()
    {
        return String.Format("FirstName {0}\nLastName {1}\nAge {2}", FirstName, LastName, Age);
    }
}

如果您只是想节省ToString手工编码,那么您当然可以结合使用这两种方法。


推荐阅读