首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >是否为ConfigurationProperty密钥生成ID?

是否为ConfigurationProperty密钥生成ID?
EN

Stack Overflow用户
提问于 2012-08-09 00:25:17
回答 2查看 571关注 0票数 0

我有一个带有修饰属性的ConfigElement,它指示它是必需的还是一个键。我想让它成为一个密钥,但是我如何生成一个密钥,这样我就不需要依赖用户来生成一个唯一的密钥了?我试着使用Guid.NewGuid(),但它给出了一个错误,说明默认值必须是常量:

代码语言:javascript
复制
An attribute argument must be a constant expression, 
typeof expression or array creation expression of an attribute parameter type

下面是我的类的样子:

代码语言:javascript
复制
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;
        }
    }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-08-09 00:30:08

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

代码语言:javascript
复制
    public MyEntryElement(ConfigElement parent)
        : base(parent)
    {
        if ( String.IsNullOrEmpty(ID) )
        {
            ID = Guid.NewGuid().ToString();
        }
    }
票数 0
EN

Stack Overflow用户

发布于 2012-08-09 00:28:44

尝试在类的ctor中分配id。

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11868926

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档