在 C# 中枚举对象的属性(字符串) [英] Enumerating through an object's properties (string) in C#

查看:40
本文介绍了在 C# 中枚举对象的属性(字符串)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有很多对象,它们有很多字符串属性.

Let's say I have many objects and they have many string properties.

是否有一种编程方式来遍历它们并输出属性名称及其值,还是必须对其进行硬编码?

Is there a programatic way to go through them and output the propertyname and its value or does it have to be hard coded?

是否有 LINQ 方法来查询字符串"类型的对象的属性并输出它们?

Is there maybe a LINQ way to query an object's properties of type 'string' and to output them?

您是否必须对要回显的属性名称进行硬编码?

Do you have to hard code the property names you want to echo?

推荐答案

使用反射.它的速度远不及硬编码的属性访问,但它可以满足您的需求.

Use reflection. It's nowhere near as fast as hardcoded property access, but it does what you want.

以下查询为对象myObject"中的每个字符串类型属性生成一个具有 Name 和 Value 属性的匿名类型:

The following query generates an anonymous type with Name and Value properties for each string-typed property in the object 'myObject':

var stringPropertyNamesAndValues = myObject.GetType()
    .GetProperties()
    .Where(pi => pi.PropertyType == typeof(string) && pi.GetGetMethod() != null)
    .Select(pi => new 
    {
        Name = pi.Name,
        Value = pi.GetGetMethod().Invoke(myObject, null)
    });

用法:

foreach (var pair in stringPropertyNamesAndValues)
{
    Console.WriteLine("Name: {0}", pair.Name);
    Console.WriteLine("Value: {0}", pair.Value);
}

这篇关于在 C# 中枚举对象的属性(字符串)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆