2012-08-08 193 views
0

我有一個裝飾屬性ConfigElement指示是否需要或一個關鍵。我想將其作爲關鍵,但是如何生成密鑰以便我不必依靠用戶來創建唯一密鑰?我試圖把Guid.NewGuid(),但它給了一個錯誤說的默認值必須是一個常數:爲ConfigurationProperty密鑰生成ID?

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; 
     } 
    } 

回答

0

如何在構造函數設置它:

public MyEntryElement(ConfigElement parent) 
     : base(parent) 
    { 
     if (String.IsNullOrEmpty(ID)) 
     { 
      ID = Guid.NewGuid().ToString(); 
     } 
    } 
0

嘗試分配ID在班級的課程中。

而且我會讓ID只讀(沒有設置)。通常不希望允許修改密鑰(僅創建)。