Treat Object Like Dictionary of Properties in C#

后端 未结 3 1134
名媛妹妹
名媛妹妹 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:03

    I don't believe there is a built-in .Net type like this already in the .Net framework. It seems like you really want to create an object that behaves a lot like a Javascript object. If so then deriving from DynamicObject may be the right choice. It allows you to create an object which when wrapped with dynamic allows you to bind directly obj.Name or via the indexer obj["Name"].

    public class PropertyBag : DynamicObject {
      private object _source;
      public PropertyBag(object source) {
        _source = source;
      }
      public object GetProperty(string name) {  
        var type = _source.GetType();
        var property = type.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
        return property.GetValue(_source, null);
      }
      public override bool TryGetMember(GetMemberBinder binder, out object result) {
        result = GetProperty(binder.Name);
        return true;
      }
      public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result) {
        result = GetProperty((string)indexes[0]);
        return true;
      }
    }
    

    You can use this to wrap any type and use both the indexer and name syntax to get the properties

    var student = new Student() { FirstName = "John", LastName = "Doe" };
    dynamic bag = new PropertyBag(student);
    Console.WriteLine(bag["FirstName"]);  // Prints: John
    Console.WriteLine(bag.FirstName);     // Prints: John
    

提交回复
热议问题