如何设置列表属性的默认值?
How do I set a DefaultValue of a list property?
我有一个助手 class 这样的:
class Helper : Settings
{
[Setting, DefaultValue(false)]
public bool DeclineData { get; set; }
// ....
[Setting, DefaultValue(new List<string>())]
public List<string> AcceptList { get; set; }
}
但是我的 DefaultValue
for 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
继承自它,这不是我的决定,因为它不是我的代码或可以更改。
我的问题是,如何为我的属性 AcceptList
设置 DefaultValue
?
虽然 Selman22 答案不会生成直接错误来设置默认值,但它不会让它序列化或反序列化数据,因为我对这个混淆的信息非常有限 API 我跟着一条不同的路线。
这不是一个直接的解决方案,而是一个解决方法,直到我弄清楚关于这个 API 的更多信息,方法是将我的 DefaultValue("")
设置为空,并将我的属性用作带有分隔符的字符串进行转换从字符串到私有属性中的列表来回我能够保存我需要的数据。
您可以在构造函数中设置属性的默认值。
class Helper : Settings
{
public Helper()
{
DeclineData = false;
AcceptList = new List<string>();
}
public bool DeclineData { get; set; }
public List<string> AcceptList { get; set; }
}
由于必须是编译时常量,所以只能设为null:
[Setting, DefaultValue(default(List<string>)]
public List<string> AcceptList { get; set; }
我有一个助手 class 这样的:
class Helper : Settings
{
[Setting, DefaultValue(false)]
public bool DeclineData { get; set; }
// ....
[Setting, DefaultValue(new List<string>())]
public List<string> AcceptList { get; set; }
}
但是我的 DefaultValue
for 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
继承自它,这不是我的决定,因为它不是我的代码或可以更改。
我的问题是,如何为我的属性 AcceptList
设置 DefaultValue
?
虽然 Selman22 答案不会生成直接错误来设置默认值,但它不会让它序列化或反序列化数据,因为我对这个混淆的信息非常有限 API 我跟着一条不同的路线。
这不是一个直接的解决方案,而是一个解决方法,直到我弄清楚关于这个 API 的更多信息,方法是将我的 DefaultValue("")
设置为空,并将我的属性用作带有分隔符的字符串进行转换从字符串到私有属性中的列表来回我能够保存我需要的数据。
您可以在构造函数中设置属性的默认值。
class Helper : Settings
{
public Helper()
{
DeclineData = false;
AcceptList = new List<string>();
}
public bool DeclineData { get; set; }
public List<string> AcceptList { get; set; }
}
由于必须是编译时常量,所以只能设为null:
[Setting, DefaultValue(default(List<string>)]
public List<string> AcceptList { get; set; }