动态类,其中属性来自列表/字典

本文关键字:列表 字典 属性 动态 | 更新日期: 2023-09-27 18:03:20

我想创建一个动态类,做以下事情:

  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. 我想把这个字典传递给一个类构造器,它把属性构建到类实例中。假设我想对每个属性都有get和set功能。例如:

    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有困难。

动态类,其中属性来自列表/字典

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