gpt4 book ai didi

c# - 作为字符串的动态属性名称

转载 作者:行者123 更新时间:2023-11-30 16:06:09 25 4
gpt4 key购买 nike

当使用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类型( 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"];

关于c# - 作为字符串的动态属性名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32661643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com