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

时间:2025-03-27 12:58:04

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();
             = "First";
             = 100;
            ("first", myfool);

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

             = 300;//会影响hashtable里面的值
            (GetFool("first").());

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

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

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

        }
    }
}


 

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

        public object Clone()
        {
            return ();
        }
    }


 

相关文章