2017-06-19 44 views
0

我想要一個配置部分,看起來像這樣:ConfigurationManager中 - 配置部分錯誤

<MailMessage> 
    <from value="[email protected]" /> 
    <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; } 
    } 
} 

任何想法可能是錯誤的?謝謝你的時間!

回答

1

尋找錯誤是可序列化的類可能令人沮喪。我建議你在VisualStudio中使用自動生成功能。下面是你如何做到這一點(非常簡單):
1.複製XML示例(到剪貼板)
2.爲XML創建新類(在您的情況下爲「MailMessageSection」)
3.在VS go Edit>Paste Special>Paste XML As Classes

我知道這不正是爲什麼從沒有工作,但使用自動生成的代碼,然後更好的做法寫在自己的原因。

希望它有幫助...