日期:2014-05-17 浏览次数:20921 次
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Reflection;
namespace WinformTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
TestClass tc1 = new TestClass();
ConfigHelper cfgHelper = new ConfigHelper("c:\\1.xml");
MessageBox.Show("Prop1:" + tc1.Prop1 + ",Prop2:" + tc1.Prop2);
cfgHelper.LoadProp<TestClass>("Test/Test1", tc1); //从xml文件中加载属性值
//此处弹出的信息为什么是"Prop1:属性1,Prop2:属性2"?
MessageBox.Show("Prop1:"+ tc1.Prop1 + ",Prop2:" + tc1.Prop2);
}
}
class ConfigHelper
{
private XmlDocument xDoc = new XmlDocument();
private string strSavePath = "";
public ConfigHelper(string strPath)
{
xDoc.Load(strPath);
this.strSavePath = strPath;
}
/// <summary>
/// 通过传入一个xPath和对象实例来获取配置文件中的信息
/// </summary>
/// <param name="xPath"></param>
/// <param name="t"></param>
/// <returns></returns>
public void LoadProp<T>(string xPath, T t)
{
XmlNode node = xDoc.SelectSingleNode(xPath);
Type type = t.GetType();
&nbs