动态属性名称为字符串

时间:2015-09-18 21:57:32

标签: c# azure dynamic azure-cosmosdb

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

这有可能吗?

1 个答案:

答案 0 :(得分:2)

System.Dynamic.ExpandoObject类型(introduced as part of the DLR)似乎接近您所描述的内容。它既可以用作动态对象,也可以用作字典(it actually is a dictionary behind the scenes)。

用作动态对象:

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

用作词典:

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