c#对象赋值,返回,和参数传递注意事项

c#对象赋值,返回,和参数传递都是引用方式进行的,用惯c++的就要注意这个特征

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        private Hashtable mMyTable = new Hashtable();

        private int mMyInt = 0;
        public Form1()
        {
            InitializeComponent();
        }

        private Fool GetFool(string strName)
        {
            return (Fool)mMyTable[strName];
        }

        private int GetInt()
        {
            return mMyInt;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Fool myfool = new Fool();
            myfool.mName = "First";
            myfool.mValue = 100;
            mMyTable.Add("first", myfool);

            //c#对象值传递都是默认传递引用
            Fool fool = (Fool)mMyTable["first"];
            fool.mValue = 200;//会影响hashtable里面的值
            MessageBox.Show(((Fool)mMyTable["first"]).mValue.ToString());

            fool.mValue = 300;//会影响hashtable里面的值
            MessageBox.Show(GetFool("first").mValue.ToString());

            //哪怕你预先new一个对象也好
            Fool fool1 = new Fool();
            fool1 = GetFool("first");
            fool1.mValue = 400;//会影响hashtable里面的值
            MessageBox.Show(GetFool("first").mValue.ToString());

            //这回才是真正的传递内存拷贝,需要实现 ICloneable 接口中的 object Clone()
            Fool fool2 = (Fool)GetFool("first").Clone();
            fool2.mValue = 500;//不会影响hashtable里面的值
            MessageBox.Show(GetFool("first").mValue.ToString());

            //注意基本数据类型还是默认传值
            int intval = GetInt();
            intval++;
            MessageBox.Show(GetInt().ToString());

        }
    }
}


 

    class Fool : ICloneable
    {
        public string mName = "";
        public int mValue = 0;

        public object Clone()
        {
            return this.MemberwiseClone();
        }
    }


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值