属性来自列表/字典的动态类

时间:2013-03-12 01:14:26

标签: c# .net dynamic properties

我想创建一个动态类,其中包含以下内容:

  1. 我有一个字典,其中键是整数,值是字符串。

    Dictionary<int, string> PropertyNames =  new Dictionary<int, string>();
    PropertyNames.Add(2, "PropertyName1");
    PropertyNames.Add(3, "PropertyName2");
    PropertyNames.Add(5, "PropertyName3");
    PropertyNames.Add(7, "PropertyName4");
    PropertyNames.Add(11,"PropertyName5");
    
  2. 我想将这个字典传递给一个类构造函数,该构造函数将Properties构建到类实例中。并且假设我想为每个属性获取和设置功能。 e.g:

    MyDynamicClass Props = new MyDynamicClass( PropertyNames );
    Console.WriteLine(Props.PropertyName1);
    Console.WriteLine(Props.PropertyName2);
    Console.WriteLine(Props.PropertyName3);
    Props.PropertyName4 = 13;
    Props.PropertyName5 = new byte[17];
    
  3. 我无法理解DLR

1 个答案:

答案 0 :(得分:1)

DynamicObject课程似乎就是你想要的。实际上,文档显示了如何完全按照您的要求进行操作。为了简洁起见,这里以精简版的形式再现:

public class DynamicDictionary : DynamicObject
{
    Dictionary<string, object> dictionary = new Dictionary<string, object>();

    public int Count
    {
        get { return dictionary.Count; }
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        string name = binder.Name.ToLower();
        return dictionary.TryGetValue(name, out result);
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        dictionary[binder.Name.ToLower()] = value;
        return true;
    }
}