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. このディクショナリを、プロパティをクラス インスタンスに構築するクラス コンストラクタに渡したいと思います。そして、これらの各プロパティに対して 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を理解できません。

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 に答える