c# - 如何在 C# 中获取对象属性名称和值的列表?
问题描述
假设我有一个简单的课程
public class Person {
string firstName;
string lastName;
int age;
.... additional properties
}
然后我有一些代码确实说
person = new Person("bob", "Smith", 27);
有没有办法(也许使用 Linq?)我可以得到一个返回的字符串
“名字鲍勃/n姓史密斯/n年龄27”
解决方案
是的,试试这个:
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
手工编码,那么您当然可以结合使用这两种方法。
推荐阅读
- python - Python Pandas 复杂分组
- haskell - Haskell websockets库不工作
- php - php preg_match 或 preg_replace 保留单词(许多语言)和所有表情符号,但不保留特殊字符
- ionic-framework - Ionic 4:如果模型是数字,则不选择离子选择
- javascript - 高(饼图)图表计算不正确
- vba - VBA代码将非空白单元格从一张纸复制到另一张纸
- python - Python正则表达式提取正斜杠之间的数字
- python - 是否可以将 Pandas groupby 对象拆分为更小的 groupby 对象?
- api - 天蓝色应用服务上的 WinHttpException
- npm - 对等依赖关系也是链接 npm 模块的开发依赖关系,它充当单独的实例