這不是一個新問題,但我一直在研究這兩天,所有我能找到的答案都是過時的或無益的。我想要做的是將一個對象放入App.config中,然後在程序啓動時加載它。 (字符串)名字,(字符串)姓氏和(int)年齡。我有一個基本的類稱爲「人」與三個自動屬性:(字符串)名字,(字符串)姓和(int)年齡。這是我的App.config文件:如何從app.config中讀取對象?
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/></startup>
<configSections>
<sectionGroup name="People">
<section
name="Person"
type="Person.Person"
/>
</sectionGroup>
</configSections>
<People>
<Person>
<Person type="Person.Person, Person">
<FirstName>Jimmy</FirstName>
<LastName>Dean</LastName>
<Age>2</Age>
</Person>
</Person>
</People>
</configuration>
這裏是我的程序:
using System;
using System.Configuration;
namespace AppConfigTest
{
class AppConfigTester
{
public static void Main(string[] args)
{
var guy = (Person.Person) ConfigurationManager.GetSection("People/Person");
Console.WriteLine(guy.FirstName);
Console.WriteLine(guy.LastName);
Console.WriteLine(guy.Age);
}
}
}
在其與ConfigurationErrorsException崩潰的時刻。任何幫助將非常感激。當App.config應該讓這樣的事情變得更簡單時,我覺得這太難了。
你在哪裏定義自定義配置部分? https://msdn.microsoft.com/en-us/library/2tw134k3.aspx – David
@David這是我錯過了什麼?我之前有一個,基於棄用的ConfigurationSettings,最終取消了它。在這一點上我很困惑。我會盡力做一個新的。 – randomraccoon