简体   繁体   中英

Dynamic property name as string

When creating a new document with DocumentDB, I would like to set the property name dynamically , currently I set SomeProperty , like this:

await client.CreateDocumentAsync("dbs/db/colls/x/" 
   , new { SomeProperty = "A Value" });

, but I would like to get the SomeProperty property name from a string so that I can access different properties using the same line of code, like this:

void SetMyProperties()
{
    SetMyProperty("Prop1", "Val 1");
    SetMyProperty("Prop2", "Val 2");
}

void SetMyProperty(string propertyName, string val)
{
    await client.CreateDocumentAsync("dbs/db/colls/x/" 
       , new { propertyName = val });
}

Is this possible somehow?

The System.Dynamic.ExpandoObject type (which was introduced as part of the DLR ) seems close to what you are describing. It can be used both as a dynamic object and as a dictionary ( it actually is a dictionary behind the scenes ).

Usage as a dynamic object:

dynamic expando = new ExpandoObject();
expando.SomeProperty = "value";

Usage as a dictionary:

IDictionary<string, object> dictionary = expando;
var value = dictionary["SomeProperty"];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM