动态属性名称作为字符串

5 c# dynamic azure azure-cosmosdb

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

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

,但我想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 });
}
Run Code Online (Sandbox Code Playgroud)

这有可能吗?

The*_*kis 8

System.Dynamic.ExpandoObject类型(作为 DLR 的一部分引入)似乎与您所描述的很接近。它既可以用作动态对象,也可以用作字典(它实际上是幕后的字典)。

用作动态对象:

dynamic expando = new ExpandoObject();
expando.SomeProperty = "value";
Run Code Online (Sandbox Code Playgroud)

用作字典:

IDictionary<string, object> dictionary = expando;
var value = dictionary["SomeProperty"];
Run Code Online (Sandbox Code Playgroud)