我想要一个如下所示的配置部分:
<MailMessage>
<from value="me@you.com" />
<subject value ="Subject goes here" />
<body value="Hello. You've got mail!" />
</MailMessage>
我已经在这个链接的第二个答案中实现了这些类: How to implement a ConfigurationSection with a ConfigurationElementCollection
现在对我来说,MailMessage部分的元素不是集合,但这应该不是问题,但是当我尝试访问该属性时收到错误:
Unrecognized element 'from'
我得到了代码部分:
private static MailMessageSection emailSection = ConfigurationManager.GetSection("MailMessage") as MailMessageSection;
以下是元素的实现:
public class MailMessageSection : ConfigurationSection
{
[ConfigurationProperty("from")]
public FromElement From
{
get { return base["from"] as FromElement; }
}
[ConfigurationProperty("subject")]
public SubjectElement Subject
{
get { return base["subject"] as SubjectElement; }
}
[ConfigurationProperty("body")]
public BodyElement Body
{
get { return base["body"] as BodyElement; }
}
}
public class FromElement : ConfigurationElement
{
[ConfigurationProperty("value")]
public string From
{
get { return base["value"] as string; }
}
}
public class SubjectElement : ConfigurationElement
{
[ConfigurationProperty("value")]
public string Subject
{
get { return base["value"] as string; }
}
}
public class BodyElement : ConfigurationElement
{
[ConfigurationProperty("value")]
public string Body
{
get { return base["value"] as string; }
}
}
任何想法都可能出错?谢谢你的时间!
答案 0 :(得分:1)
查找错误是可序列化的类可能令人沮丧。我建议你在VisualStudio中使用自动生成功能。这是你如何做到的(非常简单):
1.复制XML示例(到剪贴板)
2.为XML创建新类(在您的情况下为“MailMessageSection”)
3.在VS中转到Edit
&gt; Paste Special
&gt; Paste XML As Classes
我知道这不正是from不工作的原因,但使用自动生成的代码是更好的做法,然后自己编写。
希望它有所帮助...