动态属性名称作为字符串

动态属性名称作为字符串

本文介绍了动态属性名称作为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

,但我想获得 SomeProperty 字符串中的属性名称,这样我就可以使用同一行代码访问不同的属性,例如:

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

这可能吗?

推荐答案

类型(该类型为)似乎与您所描述的很接近。它既可以用作动态对象,也可以用作字典()。

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

用作动态对象:

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

用作字典的用法:

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

这篇关于动态属性名称作为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 22:56