Question

Je suis en train de comprendre le type DynamicObject. Nous avons trouvé cet article MSDN très claire et concise que la façon de créer et d'utiliser DynamicObject:

http://msdn.microsoft.com/en- nous / bibliothèque / system.dynamic.dynamicobject.aspx

L'article contient une simple classe DynamicDictionary héritant de DynamicObject.

Maintenant, je veux itérer sur mes propriétés DynamicObject créées dynamiquement:

dynamic d = new DynamicDictionary();
d.Name = "Myname";
d.Number = 1080;

foreach (var prop in d.GetType().GetProperties())
{
  Console.Write prop.Key;
  Console.Write prop.Value;
}

Il est évident que cela ne fonctionne pas. Je veux apprendre comment faire cela sans un changement dans ma classe DynamicDictionary, depuis que je suis vraiment en train d'apprendre à l'utiliser pour tous les types d'objets existants héritant de DynamicObject.

est la réflexion nécessaire? Je dois manquer quelque chose ...

Était-ce utile?

La solution

Did you tried DynamicDictionary.GetDynamicMemberNames() method? - http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.getdynamicmembernames.aspx

Autres conseils

I believe you'd be interested in the ExpandoObject class. The DynamicObject class is just a base where you're meant to provide all the logic. It explicitly implements the IDictionary<string, object> interface so you can access it properties or add new ones that way.

// declare the ExpandoObject
dynamic expObj = new ExpandoObject();
expObj.Name = "MyName";
expObj.Number = 1000;

// print the dynamically added properties
foreach (KeyValuePair<string, object> kvp in expObj) // enumerating over it exposes the Properties and Values as a KeyValuePair
    Console.WriteLine("{0} = {1}", kvp.Key, kvp.Value);

// cast to an IDictionary<string, object>
IDictionary<string, object> expDict = expObj;

// add a new property via the dictionary reference
expDict["Foo"] = "Bar";

// verify it's been added on the original dynamic reference
Console.WriteLine(expObj.Foo);

I had just realized that you are implementing the DynamicDictionary class and misunderstood your question. Sorry.

When used with a dynamic reference, you only have access to publicly exposed members. Since only Count is declared public (besides the other DynamicObject members), you'd need to use reflection in order to access the inner dictionary to easily get those values (if you don't intend to make any further changes).

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top