新手刚开始学c#,不太理解引用类型和值类型,还有函数传递,请教大家。为什么第一段内val没变化,第二段却变了呢[code]
using System;
using System.Collections.Generic;
using System.Text;namespace Test1
{
class Program
{
static void Main(string[] args)
{
int val = 100;
Console.WriteLine("该变量的初始值为:{0}",val);
Test(val);
Console.WriteLine("该变量此时的值为:{0}",val);
Console.Read();
}
static void Test(int getVal)
{
int temp = 10;
getVal = temp * 20;
}
}
}
[/code][code]
using System;
using System.Collections.Generic;
using System.Text;namespace test2
{
class DataTypeTest
{
public int val;
}
class Program
{
static void Main(string[] args)
{
DataTypeTest bjTest = new DataTypeTest();
objTest.val = 100;
Console.WriteLine("变量的初始值为:{0}",objTest.val);
Test(objTest);
Console.WriteLine("变量的值为:{0}",objTest.val);
Console.Read();
}
static void Test(DataTypeTest dataTest)//这里传递的是对象地址
{
int temp = 10;
dataTest.val = temp * 20;
}
}
}
using System;
using System.Collections.Generic;
using System.Text;namespace Test1
{
class Program
{
static void Main(string[] args)
{
int val = 100;
Console.WriteLine("该变量的初始值为:{0}",val);
Test(val);
Console.WriteLine("该变量此时的值为:{0}",val);
Console.Read();
}
static void Test(int getVal)
{
int temp = 10;
getVal = temp * 20;
}
}
}
[/code][code]
using System;
using System.Collections.Generic;
using System.Text;namespace test2
{
class DataTypeTest
{
public int val;
}
class Program
{
static void Main(string[] args)
{
DataTypeTest bjTest = new DataTypeTest();
objTest.val = 100;
Console.WriteLine("变量的初始值为:{0}",objTest.val);
Test(objTest);
Console.WriteLine("变量的值为:{0}",objTest.val);
Console.Read();
}
static void Test(DataTypeTest dataTest)//这里传递的是对象地址
{
int temp = 10;
dataTest.val = temp * 20;
}
}
}
{
int val = 100;
Console.WriteLine("该变量的初始值为:{0}",val);
val=Test();
Console.WriteLine("该变量此时的值为:{0}",val);
Console.Read();
}
static int Test()
{
int temp = 10;
getVal = temp * 20;
retuen getVal;
}而第二段里,因为传入的参数是objTest,故修改dataTest.val的值就相当于在主程序中直接修改objTest.val的值。
第一个例子里面传递的是值类型,所以传递的是参数的一个拷贝,叫传值。所以原来的val没有改变。第二个例子里面传递的是引用类型,传递的是一个引用,也就是传址。所以传过去的地址指向内存中的同一个对象,而你修改的是这个地址指向的对象里的内容。所以你的val的值是改变了。如果你作为初学者,我想就给你说这么多吧,其实真想搞明白,你就要搞清楚内存是怎么分配的。多看看书。