gpt4 book ai didi

c# - 如何接受 'dictionary' 数据作为自定义 .NET 属性参数?

转载 作者:数据小太阳 更新时间:2023-10-29 01:53:17 25 4
gpt4 key购买 nike

我最近发现 .NET 属性只能包含基本类型、字符串、枚举、对象和这些类型的单参数数组,如讨论的那样 here .

我需要接受 IDictionary<string, string>通过 .NET 属性,但显然我不能使用 IDictionary<string, string>由于上述原因。因此,我在这里寻找可以在这些准则范围内工作的替代方案。

// I want to do this, but can't because of the CLR limitation
[MyAttribute(Attributes = new Dictionary { { "visibility", "Condition1" }, { "myAttribute", "some-value" } })]

我想到的两个可能的选择是使用 XMLJSON在声明中(作为 .NET 属性上的字符串),可以很容易地序列化为 IDictionary<string, string>对于我的应用程序,但这会将声明变成一个冗长且容易出错的字符串,没有语法检查。

// XML
[MyAttribute(Attributes = "<items><item key='visibility' value='Condition1'/><item key='myAttribute' value='some-value'/></items>")]

// JSON
[MyAttribute(Attributes = "{ 'visibility': 'Condition1', 'myAttribute': 'some-value' }")]

如果有的话,还有比这更优雅/更直接的其他替代方案吗?

最佳答案

据我所知,您可以多次添加一个属性(编辑:如果您将 AllowMultiple 设置为 true,正如 Robert Levy 指出的那样)。因此,您可以使用多个属性,而不是对整个字典使用一个属性,每个字典条目一个,每个属性都有一个键和一个值参数。

[MyDictionaryEntry(Key = key1, Value = val1)]
[MyDictionaryEntry(Key = key2, Value = val2)]
[MyDictionaryEntry(Key = key3, Value = val3)]
[MyDictionaryEntry(Key = key4, Value = val4)]

关于c# - 如何接受 'dictionary' 数据作为自定义 .NET 属性参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21265431/

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