我一直在看这个太久了。我知道我只是在做一些愚蠢的事情,但我看不到它。在添加异常之前,我的集合始终为null。添加后,它总是被抛出。我错过了什么?
我有一个Web配置集合,如下所示:
<section name="WorkOutGroups" type="System.Configuration.WorkOutGroupsSection"/>
<WorkoutGroups>
<Workouts>
<add url="something.asp" />
<add url="/subfolder/another.asp" />
<add url="../default.asp" />
</Workouts>
</WorkoutGroups>
我的课程如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Collections;
namespace MySite.Configuration
{
public class WorkOutsGroupsSection : ConfigurationSection
{
[ConfigurationProperty("WorkOut", IsDefaultCollection = false)]
[ConfigurationCollection(typeof(WorkOutCollection))]
public WorkOutCollection WorkOut
{
get
{
var WorkOut = (WorkOutCollection)base["WorkOut"];
return WorkOut;
}
}
}
public class WorkOutCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new WorkOutElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
object result = null;
if (element is WorkOutElement)
{
result = ((WorkOutElement)element).WorkOut;
}
return result;
}
public WorkOutElement this[int index]
{
get { return (WorkOutElement)BaseGet(index); }
}
}
public class WorkOutElement : ConfigurationElement
{
[ConfigurationProperty("url", IsRequired = true, IsKey = true)]
public string WorkOut
{
get
{
return (string)this["url"];
}
set
{
this["url"] = value;
}
}
}
public static class WorkOutsGroups
{
static WorkOutsGroupsSection WorkOutsGroupsSection
{
get
{
var section = ConfigurationManager.GetSection("WorkOutsGroups")
as WorkOutsGroupsSection;
if (section != null)
{
return section;
}
throw new ConfigurationErrorsException("WorkOutsGroups Configuration not found");
}
}
public static IEnumerable<string> GetWorkOut()
{
var results = WorkOutsGroupsSection.WorkOut
.OfType<WorkOutElement>()
.Select(p => p.WorkOut);
return results.ToArray();
}
}
}
我正在实现它:
foreach (var url in Workout.GetWorkout())
{
if (link.Value.Contains(url.ToString()))
returnValue = true;
}
答案 0 :(得分:0)
拼写:
ConfigurationManager.GetSection("WorkOutsGroups")
部分名称为WorkOutGroups
而不是WorkOutsGroups
答案 1 :(得分:0)
你有
var WorkOut = (WorkOutCollection)base["WorkOut"];
在您的C#代码中,但WorkOut s 在您的配置中。
也许这就是原因。