博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
c#函数中处理对象的问题
阅读量:4587 次
发布时间:2019-06-09

本文共 1849 字,大约阅读时间需要 6 分钟。

今天做了个程序,里面有个函数处理传入的对象,需要的效果是函数中处理完对象后对象能被返回,结果对象返回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

转载于:https://www.cnblogs.com/wanfa/p/4636031.html

你可能感兴趣的文章
一个分发复制+mirror的bug
查看>>
LeetCode 520 Detect Capital
查看>>
完全教程 Aircrack-ng破解WEP、WPA-PSK加密利器[zz]
查看>>
什么是C#
查看>>
从云计算到容器到容器云
查看>>
shell 分支/循环
查看>>
api服务端接口安全
查看>>
python中的time模块
查看>>
MyBatis-Plus的简单使用
查看>>
C++学习笔记-标准库类型-Vector类型
查看>>
Oracle 树操作(select…start with…connect by…prior)
查看>>
python中的operator.itemgetter函数
查看>>
h5新特性--- 多媒体元素
查看>>
jQuery实现发送短信验证码后60秒倒计时
查看>>
【CSS】盒模型+选择器(你选择的要操作的对象)
查看>>
EM算法总结
查看>>
centos7开启防火墙和指定端口
查看>>
Android系统对话框——自己定义关闭
查看>>
词法分析器 /c++实现
查看>>
Visual Studio2012 Lua插件--BabeLua
查看>>