我有一个 Helper 类:
class Helper : Settings
{
[Setting, DefaultValue(false)]
public bool DeclineData { get; set; }
// ....
[Setting, DefaultValue(new List<string>())]
public List<string> AcceptList { get; set; }
}
但是我的DefaultValue
对于 List<string>
结果错误:
An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
我也试过 typeof(List<string>)
这也失败了。
Setting
实际上是System.Attribute
作为Settings
从它继承,这不是我的决定,因为它不是我的代码或可以更改。
我的问题是,如何设置 DefaultValue
到我的属性(property)AcceptList
?
虽然 Selman22 答案不会生成直接错误来设置默认值,但它不会让它序列化或反序列化数据,而且由于我对这个混淆 API 的信息非常有限,所以我采用了不同的方法。
这不是直接的解决方案,而是一种解决方法,直到我通过设置我的 DefaultValue("")
来了解有关此 API 的更多信息为止。清空并使用我的属性作为带有分隔符的字符串在私有(private)属性中从字符串来回转换为列表我能够保存我需要的数据。
最佳答案
因为它必须是一个编译时常量,所以你只能将它设置为null:
[Setting, DefaultValue(default(List<string>)]
public List<string> AcceptList { get; set; }
关于c# - 如何设置列表属性的默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27797944/