首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何访问属性为ConfigurationPropertyAttribute的类生成的ConfigurationProperty

如何访问属性为ConfigurationPropertyAttribute的类生成的ConfigurationProperty
EN

Stack Overflow用户
提问于 2011-09-19 16:08:38
回答 1查看 1.6K关注 0票数 1

我有一个配置很大的应用程序。每个参数的所有配置节都使用.Net ConfigurationProperty属性定义,这些属性都具有DefaultValue属性。

当我们的产品在国家之间,甚至是在一个国家的客户之间变得高度可定制时,就会有一个Configurator.exe来编辑大配置文件。

在这个Configurator.exe中,如果我能够访问已经定义的许多DefaultValue属性,那就太酷了……但是,对于如何访问这些属性生成的属性,我还不太清楚。

例如:

代码语言:javascript
复制
public class MyCollection : ConfigurationElementCollection
{
    public MyCollection ()
    {
    }

    [ConfigurationProperty(MyAttr,IsRequired=false,DefaultValue=WantedValue)]
    public MyAttributeType MyAttribute
    {
        //... property implementation
    }
}

我需要的是以编程方式访问WantedValue值,这是尽可能通用的。(否则,我将手动浏览所有定义的ConfigSections,收集每个字段的DefaultValues,然后检查配置器使用以下值.)

想想看,它应该是: MyCollection.GetListConfigurationProperty(),它将返回我可以调用属性的ConfigurationPropertyAttribute对象: Name、IsRequired、IsKey、IsDefaultCollection和DefaultValue

知道吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-09-21 14:23:04

这是我碰巧在我想要做的事情上取得成功的一门课:

我给它输入了ConfigSection类型、我想要的字段的defualt值的类型以及我想要的字段的字符串值。

代码语言:javascript
复制
public class ExtensionConfigurationElement<TConfigSection, UDefaultValue>
    where UDefaultValue : new() 
    where TConfigSection : ConfigurationElement, new()
{
    public UDefaultValue GetDefaultValue(string strField)
    {
        TConfigSection tConfigSection = new TConfigSection();
        ConfigurationElement configElement = tConfigSection as ConfigurationElement;
        if (configElement == null)
        {
            // not a config section
            System.Diagnostics.Debug.Assert(false);
            return default(UDefaultValue);
        }

        ElementInformation elementInfo = configElement.ElementInformation;

        var varTest = elementInfo.Properties;
        foreach (var item in varTest)
        {
            PropertyInformation propertyInformation = item as PropertyInformation;
            if (propertyInformation == null || propertyInformation.Name != strField)
            {
                continue;
            }

            try
            {
                UDefaultValue defaultValue = (UDefaultValue) propertyInformation.DefaultValue;
                return defaultValue;
            }
            catch (Exception ex)
            {
                // default value of the wrong type
                System.Diagnostics.Debug.Assert(false);
                return default(UDefaultValue);                
            }
        }

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

https://stackoverflow.com/questions/7473960

复制
相关文章

相似问题

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