試圖訪問ConnectionConfiguration
總是返回默認值或0
爲整數數據類型。沒有錯誤被拋出,它只是無法獲得每個屬性的值。請幫我解決這個問題。定製ConfigurationSection與sectionGroup不起作用
我在控制檯應用程序的app.config文件如下:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<sectionGroup name="templates" >
<section name="connections" type="Test.ConnectionConfiguration, Test" allowLocation="true" allowDefinition="Everywhere"/>
</sectionGroup>
</configSections>
<templates>
<connections allowed="true" port="8080">
<internal name="local" size="1344"/>
<external name="internet" value="http" />
</connections>
</templates>
</configuration>
提前的類
public class ConnectionConfiguration : ConfigurationSection
{
[ConfigurationProperty("allowed", IsRequired = true)]
public bool Allowed
{
get
{
return (bool)this["allowed"];
}
set
{
this["allowed"] = value;
}
}
[ConfigurationProperty("port", IsRequired = true)]
public int Port
{
get { return (int)this["port"]; }
set { this["port"] = value; }
}
[ConfigurationProperty("internal")]
public InternalElement Internal
{
get { return (InternalElement)this["internal"]; }
set { this["internal"] = value; }
}
[ConfigurationProperty("external")]
public ExternalElement External
{
get { return (ExternalElement)this["external"]; }
set { this["external"] = value; }
}
}
public class InternalElement : ConfigurationElement
{
[ConfigurationProperty("name", DefaultValue = "local", IsRequired = true)]
[StringValidator(InvalidCharacters = "[email protected]#$%^&*()[]{}/;'\"|\\", MinLength = 1, MaxLength = 60)]
public string Name
{
get { return (string)this["name"]; }
set { this["name"] = value; }
}
[ConfigurationProperty("size", DefaultValue = "1234", IsRequired = false)]
[IntegerValidator(ExcludeRange = false, MaxValue = 6000, MinValue = 1)]
public int Size
{
get { return (int)this["size"]; }
set { this["size"] = value; }
}
}
public class ExternalElement : ConfigurationElement
{
[ConfigurationProperty("name", DefaultValue = "local", IsRequired = true)]
[StringValidator(InvalidCharacters = "[email protected]#$%^&*()[]{}/;'\"|\\", MinLength = 1, MaxLength = 60)]
public string Name
{
get { return (string)this["name"]; }
set { this["name"] = value; }
}
[ConfigurationProperty("value", DefaultValue = "https", IsRequired = false)]
public string Value
{
get { return (string)this["value"]; }
set { this["value"] = value; }
}
}
謝謝!
ConnectionConfiguration config = new ConnectionConfiguration();
int test = config.Port; // it should be 8080 but it's 0