我有一个配置很大的应用程序。每个参数的所有配置节都使用.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
知道吗?
发布于 2011-09-21 14:23:04
这是我碰巧在我想要做的事情上取得成功的一门课:
我给它输入了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);
}
}https://stackoverflow.com/questions/7473960
复制相似问题