【问题标题】:Dynamic Class where properties come from a list/dictionary [duplicate]属性来自列表/字典的动态类[重复]
【发布时间】:2013-03-12 10:34:33
【问题描述】:

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

  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

【问题讨论】:

  • 看到这篇文章,我想这会有所帮助:stackoverflow.com/questions/2974008/…
  • 您基本上是在描述ExpandoObject。看看:msdn.microsoft.com/en-us/library/…
  • 哦,好吧,我认为这很简单。我从来不知道 ExpandoObject。
  • 只是出于好奇,有谁知道为什么 MSFT 决定将类命名为 ExpandoObject 而不是 ExpandObject?这似乎是一个错字。
  • 仅供参考,当您使用 ExpandoObject 或 DynamicObject 等类型时,您将放弃几乎所有编译时检查并牺牲性能。

标签: c# .net dynamic properties


【解决方案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;
    }
}

【讨论】:

    猜你喜欢
    • 2021-05-25
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 2011-07-30
    • 1970-01-01
    • 2017-03-10
    • 1970-01-01
    相关资源
    最近更新 更多