今天做了个程序,里面有个函数处理传入的对象,需要的效果是函数中处理完对象后对象能被返回,结果对象返回null值;
开始程序如下:
public partial class Form1 : Form { public Form1() { InitializeComponent(); }private void DoPayInfo(PayInfoBean pinfo) { pinfo = new PayInfoBean(); pinfo.ResultCode = "1"; pinfo.Msg = "test"; pinfo.Tips = "测试成功"; }private void button1_Click(object sender, EventArgs e) { PayInfoBean pinfo = new PayInfoBean(); DoPayInfo(pinfo); MessageBox.Show(pinfo.Msg); } }public class PayInfoBean { private string resultCode; private string msg; private string tips;public string Tips { get { return tips; } set { tips = value; } }public string ResultCode { get { return resultCode; } set { resultCode = value; } }public string Msg { get { return msg; } set { msg = value; } }} |
于是在网上各种找资料,终于解决问题。代码修改如下:
public partial class Form1 : Form { public Form1() { InitializeComponent(); }private void DoPayInfo(PayInfoBean pinfo) { PayInfoBean newpinfo = new PayInfoBean(); newpinfo.ResultCode = "1"; newpinfo.Msg = "test"; newpinfo.Tips = "测试成功";newpinfo.CopyProperty(pinfo); //复制对象引用到传入的对象中 }private void button1_Click(object sender, EventArgs e) { PayInfoBean pinfo = new PayInfoBean(); DoPayInfo(pinfo); MessageBox.Show(pinfo.Msg); } }public class PayInfoBean { private string resultCode; private string msg; private string tips;public void CopyProperty(PayInfoBean dest) { dest.ResultCode = resultCode; dest.Msg = msg; dest.Tips = tips; }public string Tips { get { return tips; } set { tips = value; } }public string ResultCode { get { return resultCode; } set { resultCode = value; } }public string Msg { get { return msg; } set { msg = value; } }} |
最后问题终于解决了,发现在函数中不能将传入的对象重新创建,如果重新创建对象,传入的对象指针就会改变;而我之所以必须用传入对象进行处理,是因为之前的函数早就存在,那个对象是后来加入的,为了不改变原来函数的返回值,所以必须用传入对象处理;
参考资料:http://www.cnblogs.com/lidabo/archive/2012/03/12/2392304.html