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

后端 未结 5 844
别那么骄傲
别那么骄傲 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);
    }
    
    0 讨论(0)
  • 2020-11-29 01:32

    How about something like this?

    public string Prop1
    {
        get { return dic["Prop1"]; }
        set { dic["Prop1"] = value; }
    }
    
    public string Prop2
    {
        get { return dic["Prop2"]; }
        set { dic["Prop2"] = value; }
    }
    
    private Dictionary<string, string> dic = new Dictionary<string, string>();
    public IEnumerable<KeyValuePair<string, string>> AllProps
    {
        get { return dic.GetEnumerator(); }
    }
    
    0 讨论(0)
  • 2020-11-29 01:41

    You can use reflection to do this... . there is a decent article at CodeGuru, but that may be more than you are looking for... you can learn from it, and then trim it to your needs.

    0 讨论(0)
  • 2020-11-29 01:45

    If your goal is simply to output the data stored in the object's properties using a human-readable format, I prefer to simply serialize the object into JSON format.

    using System.Web.Script.Serialization;
    //...
    
    string output = new JavaScriptSerializer().Serialize(myObject);
    
    0 讨论(0)
  • 2020-11-29 01:47

    You can get all the properties of a type by using the GetProperties method. You can then filter this list using the LINQ Where extension method. Finally you can project the properties using the LINQ Select extension method or a convenient shortcut like ToDictionary.

    If you want to limit the enumeration to properties having of type String you can use this code:

    IDictionary<String, String> dictionary = myObject.GetType()
      .GetProperties()
      .Where(p => p.CanRead && p.PropertyType == typeof(String))
      .ToDictionary(p => p.Name, p => (String) p.GetValue(myObject, null));
    

    This will create a dictionary that maps property names to property values. As the property type is limited to String it is safe to cast the property value to String and the type of the returned type is IDictionary<String, String>.

    If you instead want all properties you can do it like this:

    IDictionary<String, Object> dictionary = myObject.GetType()
      .GetProperties()
      .Where(p => p.CanRead)
      .ToDictionary(p => p.Name, p => p.GetValue(myObject, null));
    
    0 讨论(0)
提交回复
热议问题