Enumerating through an object's properties (string) in C#

后端 未结 5 954
别那么骄傲
别那么骄傲 2020-11-29 01:12

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

5条回答
  •  迷失自我
    2020-11-29 01:31

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

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

    Usage:

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

提交回复
热议问题