日期:2014-05-17  浏览次数:20867 次

关于C#反射的疑问,传入方法的对象的属性值会被更改?
今天在写一个东西的时候发现了一个奇怪的现象,我new了一个对象后传入了一个方法中,在此方法中用反射得到方法的类型、属性等之后对传入的对象副本进行赋值,可是我发现它竟然会影响到原对象,这是为什么,传入的不是对象副本吗?下面的代码(winform):

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