创建具有反射支持的动态字典?

时间:2016-01-13 10:01:20

标签: c# dictionary dynamic

这个怎么样?我正在考虑创建一个支持反射的动态字典,通过覆盖它来键入并将其作为PropertyInfo返回它的字典条目。我还没有实现整个Type和PropertyInfo类,但它看起来像下面的代码。你认为这是一个好主意还是坏主意?它甚至可能吗?

public class DynamicDictionary : DynamicObject
{
  private Dictionary<string, object> _dictionary;

  public DynamicDictionary()
  {
    _dictionary = new Dictionary<string, object>();
  }

  public IEnumerable<Tuple<string, Type>> GetProperties()
  {
    return _dictionary.Select(kvp => new Tuple<string, Type>(kvp.Key, kvp.Value.GetType()));
  }

  public override bool TryGetMember(GetMemberBinder binder, out object result)
  {
    object data;
    if (!_dictionary.TryGetValue(binder.Name, out data))
    {
      throw new KeyNotFoundException("There's no key by that name");
    }

    result = data;

    return true;
  }

  public override bool TrySetMember(SetMemberBinder binder, object value)
  {
    if (_dictionary.ContainsKey(binder.Name))
    {
      _dictionary[binder.Name] = value;
    }
    else
    {
      _dictionary.Add(binder.Name, value);
    }

    return true;
  }

  public Type GetType()
  {
    return new DynamicType(this);
  }
}

public class DynamicType : Type
{
  private readonly DynamicDictionary _instance;

  public DynamicType(DynamicDictionary instance)
  {
    _instance = instance;
  }

  public override System.Reflection.Assembly Assembly
  {
    get { return _instance.GetType().Assembly; }
  }

  public override string AssemblyQualifiedName
  {
    get { return _instance.GetType().AssemblyQualifiedName; }
  }

  public override System.Reflection.PropertyInfo[] GetProperties(System.Reflection.BindingFlags bindingAttr)
  {
    return _instance.GetProperties().Select(p => new DynamicPropertyInfo(p.Item1)).ToArray();
  }
}

public class DynamicPropertyInfo : PropertyInfo
{
  public DynamicPropertyInfo(string name)
  {
    _name = name;
  }

  private string _name;

  public override string Name
  {
    get
    {
      return _name;
    }
  }
}

0 个答案:

没有答案