2011-09-19 56 views
1

我有一个非常大的配置应用程序。 每个参数的所有配置部分都使用.Net ConfigurationProperty属性定义,它们都具有DefaultValue属性。如何访问为具有属性的类生成的ConfigurationPropertyAttribute ConfigurationProperty

由于我们的产品在各个国家甚至是一个国家的客户之间变得非常可定制,因此有一个Configurator.exe可以编辑大型配置文件。

在这个Configurator.exe中,如果我可以访问许多已定义的许多DefaultValue属性,那将是非常酷的......但是,我没有关于如何访问这些属性的一个单独想法属性生成的属性。

例如为:

public class MyCollection : ConfigurationElementCollection 
{ 
    public MyCollection() 
    { 
    } 

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

我需要的是通过编程访问该值WantedValue,最一般越好。 (否则,我要手动浏览所有定义的部分,收集每个字段的DefaultValues,然后检查我的配置器使用这些值...)

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

任何想法?

回答

0

这是我碰巧实现其成功在什么我想要做的类:

我与ConfigSection类型,我想现场的defualt值的类型,以及字符串值喂它我想要的领域。

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); 
    } 
} 
相关问题