带有字典的默认值属性

Default Value attribute with a dictionary

我正在尝试使用默认值属性 Default Value Documentation

所以我知道如何使用字符串设置默认属性

 [DefaultValue("This is the message")]

但是如何为字典设置默认值?

我试过了

   [DefaultValue(new Dictionary<string, string>() { { "Test", "test" } })]

但是我收到这个错误

Error CS0182 An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

你不能在任何属性中使用字典,但你可以尝试添加你自己的键+值属性。

我不知道你想如何使用它,但我建议你试试:

public class DictionaryDefaultAttribute : DefaultValueAttribute
{
    public DictionaryDefaultAttribute(string key, string value) 
        : base(new Dictionary<string, string>() {{key, value}})
    {
    }
}