2

我想创建一个动态类,执行以下操作:

  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. 我想将此字典传递给将属性构建到类实例中的类构造函数。并且假设我想为每个属性同时拥有获取和设置功能。例如:

    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];
    

我无法理解DLR

4

1 回答 1

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;
    }
}
于 2013-03-12T02:31:30.573 回答