动态 属性 名称作为字符串

Dynamic property name as string

使用 DocumentDB 创建新文档时,我想动态设置 属性 名称 ,目前我设置 SomeProperty,如下所示:

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

,但我想从字符串中获取 SomeProperty 属性 名称,以便我可以使用同一行代码访问不同的属性,如下所示:

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

这有可能吗?

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).

作为动态对象的用法:

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

用作字典:

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