通过在C#中一个对象的属性(字符串)枚举字符串、属性、对象

2023-09-02 10:24:20 作者:那与爱无关″

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

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);
}