为什么在函数内部传递和修改源DataSet值时会对其进行更改? [英] Why source DataSet value getting changed while passed and modified inside a function?

查看:94
本文介绍了为什么在函数内部传递和修改源DataSet值时会对其进行更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在函数内部传递和修改源DataSet值时会对其进行更改?

Why source DataSet value getting changed while passed and modified inside a function?

DataSet output = new DataSet();
            SqlConnection con = new SqlConnection("Data                 Source=SERVER;Initial Catalog=Database;Integrated Security=True;");
            SqlCommand cmd = new SqlCommand("select 'value1'",con);
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            adp.Fill(output);
            Test(output);
            MessageBox.Show(output.Tables[0].Rows[0][0].ToString());

        public void Test(DataSet dataSet)
        {
            MessageBox.Show(dataSet.Tables[0].Rows[0][0].ToString());
            //Modifying value here is getting effected to the source DataSet, Is it always passed by ref?

            dataSet.Tables[0].Rows[0][0] = "value2";

        }

推荐答案

dataSet参数是对对象的引用.引用是按值传递的,因此更改它不会影响原始值.因此,以下代码仅在函数内部有效,而不会在调用Test(output)中更改output变量的值.
The dataSet parameter is a reference to an object. The reference was passed by value and so changing it will not effect the original value. So the below code will only have effect inside the function and will not change the value of the output variable from the call Test(output).
public void Test(DataSet dataSet)
{
    dataSet = new DataSet();
}


但是,当使用语句


But when use the statement

dataSet.Tables[0].Rows[0][0] = "value2";

在函数中,您正在更改dataSet所引用的对象,这将按预期更改对象中的值.

inside the function you are changing the object being referenced by dataSet which changes the values in the object as expected.


这篇关于为什么在函数内部传递和修改源DataSet值时会对其进行更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆