【问题标题】:Generate ID for ConfigurationProperty key?为 ConfigurationProperty 键生成 ID?
【发布时间】:2012-08-05 19:45:30
【问题描述】:

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

【问题讨论】:

    标签: c# asp.net .net c#-4.0 configuration


    【解决方案1】:

    尝试在类的ctor中分配id。

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2019-01-01
        • 1970-01-01
        • 2011-11-20
        • 2011-11-28
        • 1970-01-01
        • 2015-05-03
        • 2020-11-15
        • 2013-10-05
        • 1970-01-01
        相关资源
        最近更新 更多