嗨,大家要在項目中實現自定義配置部分。但是,我不明白的東西不工作。使用配置元素集合實現自定義部分c#
我的App.config,看起來像這樣:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="DepartmentConfigurationSection" type="Statistics.Config.DepartmentSection , Program1"/>
</configSections>
<s>
<Cash>
<add Number="1" Name="Money" />
</Cash>
<Departments>
<add Id="1" Name="x" />
<add Id="2" Name="y" />
</Departments>
</s>
</configuration>
我創建了一個名爲DepartmentSection.cs文件cointains將ConfigurationElement,ConfigurationElementCollection中和的ConfigurationSection。 類是這樣的:
public class DepartmentConfig : ConfigurationElement
{
public DepartmentConfig() { }
public DepartmentConfig(int id, string name)
{
Id = id;
Name = name;
}
[ConfigurationProperty("Id", IsRequired = true, IsKey = true)]
public int Id
{
get { return (int)this["Id"]; }
set { this["Id"] = value; }
}
[ConfigurationProperty("Name", IsRequired = true, IsKey = false)]
public string Name
{
get { return (string)this["Name"]; }
set { this["Name"] = value; }
}
}
public class DepartmentCollection : ConfigurationElementCollection
{
public DepartmentCollection()
{
Console.WriteLine("ServiceCollection Constructor");
}
public DepartmentConfig this[int index]
{
get { return (DepartmentConfig)BaseGet(index); }
set
{
if (BaseGet(index) != null)
{
BaseRemoveAt(index);
}
BaseAdd(index, value);
}
}
public void Add(DepartmentConfig depConfig)
{
BaseAdd(depConfig);
}
public void Clear()
{
BaseClear();
}
protected override ConfigurationElement CreateNewElement()
{
return new DepartmentConfig();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((DepartmentConfig)element).Id;
}
public void Remove(DepartmentConfig depConfig)
{
BaseRemove(depConfig.Id);
}
public void RemoveAt(int index)
{
BaseRemoveAt(index);
}
public void Remove(string name)
{
BaseRemove(name);
}
}
public class DepartmentConfigurationSection : ConfigurationSection
{
[ConfigurationProperty("Departments", IsDefaultCollection = false)]
[ConfigurationCollection(typeof(DepartmentCollection),
AddItemName = "add",
ClearItemsName = "clear",
RemoveItemName = "remove")]
public DepartmentCollection Departments
{
get
{
return (DepartmentCollection)base["Departments"];
}
}
}
我試圖從處理程序得到的集合,但不success.I試過這樣的,但給我這個錯誤:「無法初始化系統配置」。
DepartmentConfigurationSection serviceConfigSection =
ConfigurationManager.GetSection("s") as DepartmentConfigurationSection;
DepartmentConfig serviceConfig = serviceConfigSection.Departments[0];
請幫幫我!謝謝..
我糾正了錯誤,但現在appares這樣的:「錯誤,同時爲S上的配置節處理程序:無法加載類型」 Program1.Config.DepartmentConfigurationSection'從程序集'Program1'...爲什麼? – puti26
這意味着'Program1'程序集中沒有類'Program1.Config.DepartmentConfigurationSection'什麼名稱空間是'DepartmentConfigurationSection'下的?type屬性應該是' type =「[namespace],[assembly]」',所以在你的情況下我**認爲**應該是'type =「Statistics.Config.DepartmentConfigurationSection,Program1」'。 – rsbarro
Th名字空間是'namespace Statistics.Config'。在Program1程序集中沒有上課時你的意思是什麼? – puti26