我需要在我的自定义配置部分执行类似的操作:
ConfigurationManager.ConnectionStrings["mongodb"]上面的字符串"mongodb“是我用来访问System.Configuration.ConnectionStringSettings.类型的de元素的键。我也想对我的自定义收藏做同样的事情:
[ConfigurationCollection(typeof(Question))]
public class QuestionCollection : ConfigurationElementCollection
{
public override bool IsReadOnly()
{
return false;
}
protected override ConfigurationElement CreateNewElement()
{
return new Question();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((Question)element).id;
}
//Is here?
public Question this[int idx]
{
get {
return (Question)BaseGet(idx);
}
set
{
if (BaseGet(idx) != null)
BaseRemoveAt(idx);
BaseAdd(idx, value);
}
}
}我在想上面提到的方法是得到我想要的东西的方法.但我不知道怎么..。我想要访问的键类型是整数。
假设我有以下配置:
<securityQuestions>
<questions>
<add id="3" value="What is your name?" default="true"/>
<add id="4" value="What is your age?"/>
</questions>
</securityQuestions>如何使用...Section.Questions3访问第一个元素(...Section.Questions3)
发布于 2013-10-11 06:30:14
我假设您的自定义配置部分的名称是SecurityQuestionsSection。
我假设你有这样的代码:
public class SecurityQuestionsSection: ConfigurationSection
{
[ConfigurationProperty("questions", IsRequired = true, IsDefaultCollection = true)]
public QuestionCollection Questions
{
get
{
return (QuestionCollection)base["questions"];
}
}
}如果是这样的话,您可以这样写:
var customConfigSection = (SecurityQuestionsSection)ConfigurationManager
.GetSection("securityQuestionsSection");
var firstElementId = customConfigSection.Questions[0].Id; 希望这能有所帮助!
编辑:通过它的键访问配置元素--您有两个选项。
1)您可以在类之外使用Linq:
var elementWithIdOfThree = customConfigSection.Questions
.FirstOrDefault(item => item.Id == 3); 2)或者可以为QuestionCollection类添加一个方法,如下所示:
public Question GetQuestionWithId(int id)
{
return this.FirstOrDefault(item => item.Id == id);
}发布于 2013-10-11 11:45:58
感谢阿列克西·契波沃伊的建议。解决办法如下:
[ConfigurationCollection(typeof(Question))]
public class QuestionCollection : ConfigurationElementCollection
{
public override bool IsReadOnly()
{
return false;
}
protected override ConfigurationElement CreateNewElement()
{
return new Question();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((Question)element).id;
}
public Question this[int id]
{
get
{
return this.OfType<Question>().FirstOrDefault(item => item.id == id);
}
}
}发布于 2015-02-04 20:45:50
您可以强制此重载按其键检索configurationElement项:
public Question GetQuestion(int id)
{
get
{
return (Question)this.BaseGet((object)id);
}
}https://stackoverflow.com/questions/19309316
复制相似问题