开发者

How to store integer in config file but retrieve it as an enumeration?

I have a class that represents a configuration element:

public class ProductLevelConfigurationElement 
    : ConfigurationElement, IProductLevelConfiguration
{
    [ConfigurationProperty("level",IsKey = true, IsRequired = true)]
    public ProductLevel Level
    {
        get { return (ProductLevel)this["level"]; }
        set { this["level"] = value; }
    }
    [ConfigurationProperty("include")]
    public bool Include
    {
        get { return (bool)this["include"]; }
        set { this["include"] = value; }
    }
}

In web.co开发者_运维知识库nfig I want to configure it like:

<item level="1" include="true" />

But it doesn't work. If I put MainProduct in level attribute (one of the values of this enum) then it works perfect.

Any thoughts on how to solve this?


You can hack around it by changing your configuration property to type int, making it private and create a new property on your class.

[ConfigurationProperty("level", IsKey = true, IsRequired = true)]
private int LevelFromConfig
{
    get { return (int)this["level"]; }
    set { this["level"] = value; }
}

public ProductLevel Level
{
    get { return (ProductLevel)this.LevelFromConfig; }
}

The above code is provided as a simple example with no error checking of any kind.


I have found solution.

You can override DeserializeElement method

protected override void DeserializeElement(System.Xml.XmlReader reader, bool serializeCollectionKey)
{
 Level = (ProductLevel) int.Parse(reader.GetAttribute("level"));
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜