C#中参数传递的问题

来源:百度知道 编辑:UC知道 时间:2024/05/29 18:13:53
有下面两段类似的代码:
public static void Main()
{
object oRef = new object();
RefWithRef(ref oRef);
Console.WriteLine(oRef.ToString());
}

static void RefWithRef(ref object o)
{
o = new MyStruct();
Console.WriteLine(o.ToString());
}
结果为ConsoleApplication1.pp+MyStruct
ConsoleApplication1.pp+MyStruct

另一段:
public static void Main()
{
object oRef = new object();
RefWithRef(oRef);
Console.WriteLine(oRef.ToString());
}

static void RefWithRef(object o)
{
o = new MyStruct();
Console.WriteLine(o.ToString());
}
结果为:ConsoleApplication1.pp+MyStruct
System.Object
为什么这两段结果不一样啊?第二段传递参数时只是少了个ref关键字,但这对引用类型没影响吧?只对值类型有影响啊

ref是传的引用,给你说个小用处吧,如果你想一个函数返回多个返回值时,可以用ref关键字,传入的参数在函数内改变,之前执行函数之前的初始化都是不管用的。例如:public void GetCount(ref int failed,ref int suc)
{
string cmd_text = "select count(*) from temp where state ='发送成功'";
string cmd_text1 = "select count(*) from temp where state ='发送失败'";
SqlCommand cmd1 = new SqlCommand(cmd_text, con);
SqlCommand cmd2 = new SqlCommand(cmd_text1, con);
failed = Convert.ToInt32( cmd2.ExecuteScalar());
suc = Convert.ToInt32 ( cmd1.ExecuteScalar());
}
然后调用函数:

private void button14_Click_1(object sender, EventArgs e)//统计发送失败成功数目
{
int failed = 0;
int suc = 0;
int count = failed + suc;
sqlHelper h = new sqlHelper();
h.GetCount(ref failed ,ref suc);
label6.Text = "共有任务数:"+