c# - 如何设置列表属性的默认值?

标签 c# .net

我有一个 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/

相关文章:

.net - 样式化 ContentControl

.net - 调用 WebMethod,传递 Dictionary<string, string> 作为参数

c# - 在 try 语句内调用 Monitor.Enter 与在 try 语句外调用它

C#:使用虚拟对象初始化事件处理程序

.net - 有什么理由将 .snk 文件与项目源一起发送?

c# - 在服务器上: Getting IP Address of Connected Clients

.net - 使用 Python 的 P2P RDP

使用 Visual Studio 2012 创建的 C# Windows 窗体应用程序无法在 Windows XP 上运行

c# - 统一读取和解析 C# 中的 Json 文件

c# - ASP.NET核心: How to add a second model to my View