提问人:Dharun 提问时间:6/7/2023 最后编辑:Dharun 更新时间:6/7/2023 访问量:24
在 ConfigurationElementCollection 中添加新的 ConfigurationElement 会引发只读异常
Add new ConfigurationElement in ConfigurationElementCollection throws Read-only exception
问:
我有一个.config文件,我需要在ConfigurationElementCollection下添加新的ConfigurationElement,我已经按照微软的文档进行了操作,并实现了 https://learn.microsoft.com/en-us/dotnet/api/system.configuration.configurationelementcollection?view=windowsdesktop-7.0 的所有内容。
但 BaseAdd 重写方法始终会引发只读异常。
这是我的配置文件数据,我正在尝试在testelements属性下添加新元素。
<testElements>
<testElements>
<clear/>
<add name="test"
model = "model"/>
这是 ConfigurationElement 类:
public class TestElements: ConfigurationElement
{
public TestElements()
{
}
public TestElements(string elementName)
{
Name = elementName;
}
[ConfigurationProperty("name",
IsRequired = true, IsKey = true)]
public string Name
{
get
{
return ((string)this["name"]);
}
set
{
this["name"] = value;
}
}
[ConfigurationProperty("model", IsRequired = true, IsKey = true)]
public string ModelName
{
get
{
return (string)this["model"];
}
set
{
this["model"] = value;
}
}
}
我的configurationelementCollection类:
public class TestElementsCollection : ConfigurationElementCollection
{
public TestElementsCollection()
{
}
public override
ConfigurationElementCollectionType CollectionType
{
get
{
return
ConfigurationElementCollectionType.AddRemoveClearMap;
}
}
protected override
ConfigurationElement CreateNewElement()
{
return new ServiceRouteDefaults();
}
protected override
ConfigurationElement CreateNewElement(
string elementName)
{
return new TestElements(elementName);
}
public new string AddElementName
{
get
{ return base.AddElementName; }
set
{ base.AddElementName = value; }
}
public new string ClearElementName
{
get
{ return base.ClearElementName; }
set
{ base.ClearElementName = value; }
}
public new string RemoveElementName
{
get
{ return base.RemoveElementName; }
}
public void Add(TestElements url)
{
BaseAdd(url);
// Add custom code here.
}
protected override void
BaseAdd(ConfigurationElement element)
{
BaseAdd(element, false);
// Add custom code here.
}
public void Remove(TestElements url)
{
string key = GetElementKey(url).ToString();
if (BaseIndexOf(url) >= 0)
BaseRemove(key.ToLower());
}
public void RemoveAt(int index)
{
BaseRemoveAt(index);
}
public void Remove(string name)
{
BaseRemove(name);
}
public void Clear()
{
BaseClear();
// Add custom code here.
}
尝试使用调用 Add 方法 -> Add(new TestElements() {Name = “check”, ModelName =“checkname”}) -> 时,这会抛出 Configuration 是只读的,看起来 BaseAdd 失败。我做错了什么吗?
答: 暂无答案
评论