1

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

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

在这个 Configurator.exe 中,如果我可以访问许多已定义的 DefaultValue 属性,那就太酷了……但是,我不知道如何访问由属性。

例如:

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

任何想法 ?

4

1 回答 1

0

这是我碰巧完成的课程,它成功地完成了我想做的事情:

我用 ConfigSection 类型、我想要的字段的默认值的类型以及我想要的字段的字符串值来提供它。

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);
    }
}
于 2011-09-21T14:23:04.470 回答