我有一个带有修饰属性的ConfigElement,它指示它是必需的还是一个键。我想让它成为一个密钥,但是我如何生成一个密钥,这样我就不需要依赖用户来生成一个唯一的密钥了?我试着使用Guid.NewGuid(),但它给出了一个错误,说明默认值必须是常量:
An attribute argument must be a constant expression,
typeof expression or array creation expression of an attribute parameter type下面是我的类的样子:
public class MyEntryElement : ConfigElement
{
#region Constructor
public MyEntryElement(ConfigElement parent)
: base(parent)
{
}
#endregion
#region Properties
[ConfigurationProperty("id", DefaultValue = Guid.NewGuid(), IsRequired = true, IsKey = true)]
[ObjectInfo(Title = "ID", Description = "Defines the id of the entry.")]
public string ID
{
get
{
return (string)this["id"];
}
set
{
this["id"] = value;
}
}
[ConfigurationProperty("note", DefaultValue = "", IsRequired = true)]
[ObjectInfo(Title = "Note", Description = "Defines the note of the entry.")]
public string Note
{
get
{
return (string)this["note"];
}
set
{
this["note"] = value;
}
}发布于 2012-08-09 00:30:08
如何在你的构造函数中设置它:
public MyEntryElement(ConfigElement parent)
: base(parent)
{
if ( String.IsNullOrEmpty(ID) )
{
ID = Guid.NewGuid().ToString();
}
}发布于 2012-08-09 00:28:44
尝试在类的ctor中分配id。
我会将ID设为只读(未设置)。通常不希望允许密钥被修改(仅创建)。
https://stackoverflow.com/questions/11868926
复制相似问题