App.Config怎么中存放自定义类型

1.将自定义配置信息填写到App.Config文件中。比如:

<configSections>
<section name="Student" type="?" />
</configSections>
<Student type="?">
<age>100</age>
<Name>llllzzz</Name>
</Student>

2.实现两个类。一个是代表Student的实体类,一个是创建Student实体的类。并把相应的类填写到上面"?"的位置。

public class Student
{
public string age;
public string Name;
}
public class ConfigSectionHandler : IConfigurationSectionHandler
{
public ConfigSectionHandler() : base()
{
}

public object Create(object parent, object configContext, System.Xml.XmlNode section)
{
XPathNavigator xNav
= section.CreateNavigator();
string typeOfObject = (string)xNav.Evaluate("string(@type)");
Type t
= Type.GetType(typeOfObject);
XmlSerializer ser
= new XmlSerializer(t);
XmlNodeReader xNodeReader
= new XmlNodeReader(section);
return ser.Deserialize(xNodeReader);

//Student stu = new Student();
//stu.age = "100";
//stu.Name = "lllzzz";
//return stu;
}

}

3.ok。现在就可以读取自定义配置了。

ConfigSectionObjects.Student st = (ConfigSectionObjects.Student)ConfigurationSettings.GetConfig("Student");

Console.WriteLine(
"年龄: {0}", st.age);
Console.WriteLine(
"姓名: {0}", st.Name);
原文地址:https://www.cnblogs.com/cnbwang/p/1978356.html