Treat Object Like Dictionary of Properties in C#

后端 未结 3 1137
名媛妹妹
名媛妹妹 2020-12-14 19:35

I want to be able to access property values in an object like a dictionary, using the name of the property as a key. I don\'t really care if the values are returned as objec

3条回答
  •  暖寄归人
    2020-12-14 20:18

    I have this extension method, probably the simplest it can get:

    public static Dictionary ToPropertyDictionary(this object obj)
    {
        var dictionary = new Dictionary();
        foreach (var propertyInfo in obj.GetType().GetProperties())
            if (propertyInfo.CanRead && propertyInfo.GetIndexParameters().Length == 0)
                dictionary[propertyInfo.Name] = propertyInfo.GetValue(obj, null);
        return dictionary;
    }
    

    Now you can do:

    object person = new { Name = "Bob", Age = 45 };
    var lookup = person.ToPropertyDictionary();
    string name = (string)lookup["Name"];
    lookup["Age"] = (int)lookup["Age"] + 1; // indeed editable
    

    Note:

    1. that this dictionary is case-sensitive (you can trivially extend it passing the right StringComparer).

    2. that it ignores indexers (which are also properties) but it's up to you to work on it.

    3. that the method is not generic considering it doesn't help boxing because internally it calls obj.GetType, so it boxes anyway at that point.

    4. that you get only the "readable" properties (otherwise you dont get the values held in it). Since you want it to be "writable" as well then you should use CanWrite flag as well.

提交回复
热议问题