首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

关于C#反射的疑点,传入方法的对象的属性值会被更改

2013-06-19 
关于C#反射的疑问,传入方法的对象的属性值会被更改?今天在写一个东西的时候发现了一个奇怪的现象,我new了

关于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();
            PropertyInfo[] pInfos = type.GetProperties();
            foreach (PropertyInfo pInfo in pInfos)


            {
                foreach (XmlNode cldNode in node.ChildNodes)
                {
                    XmlElement newElement = (XmlElement)cldNode;
                    if (cldNode.Name == pInfo.Name)
                    {
                        Object v = Convert.ChangeType(cldNode.InnerText, pInfo.PropertyType);
                        pInfo.SetValue(t, v, null);
                        break;
                    }
                }
            }
        }
    }

    public class TestClass
    {
        public string Prop1 { get; set; }
        public string Prop2 { get; set; }
    }
}


用于测试的1.xml中的内容:

<?xml version="1.0" encoding="utf-8"?>
<Test>
  <Test1>
  <Prop1>属性1</Prop1>
  <Prop2>属性2</Prop2>
  </Test1>
</Test>

C#
[解决办法]
什么是你说的“对象副本”呢?

代码 pInfo.SetValue(t, v, null); 这里的 t 怎么就是副本呢?

热点排行