0

我有一个带有修饰属性的 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;
        }
    }
4

2 回答 2

0

尝试在类的 ctor 中分​​配 id。

我会让 ID 只读(不设置)。通常不希望允许修改密钥(仅创建)。

于 2012-08-08T16:28:44.153 回答
0

如何在构造函数中设置它:

    public MyEntryElement(ConfigElement parent)
        : base(parent)
    {
        if ( String.IsNullOrEmpty(ID) )
        {
            ID = Guid.NewGuid().ToString();
        }
    }
于 2012-08-08T16:30:08.280 回答