【问题标题】:How to access the ConfigurationPropertyAttribute generated for a class with attributes ConfigurationProperty如何访问为具有 ConfigurationProperty 属性的类生成的 ConfigurationPropertyAttribute
【发布时间】:2011-11-20 09:33:24
【问题描述】:

我有一个配置相当大的应用程序。 每个参数的所有配置部分都使用 .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,尽可能通用。 (否则我要手动浏览所有定义的 ConfigSection,收集每个字段的 DefaultValues,然后检查我的配置器使用这些值...)

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

有什么想法吗?

【问题讨论】:

    标签: c# .net configurationproperty


    【解决方案1】:

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

    我用 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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-03-03
      • 2012-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多