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

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

问题描述

让我们说我有很多的对象,他们有许多字符串属性。

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

有没有一种程序化的方式通过他们去和输出propertyName的,其价值还是它必须是硬codeD?

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?

你有没有为C的属性名称要呼应硬$ C $?

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

推荐答案

使用反射。这是远不一样快,硬codeD属性访问,但你想要做什么。

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

下面的查询生成一个匿名类型与名称和Value属性为对象中的每个字符串类型属性myObject的

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天全站免登陆