请教 pass by value or reference 的问题# DotNet - 窗口里的风景
o*a
1 楼
今天学pass by value or ref.
有点疑问, 如果说string 在c#里面是reference type的话,为什么我下面的例子中m
is still cate , but not mouse.
static void Main(string[] args)
{
string m = "cat";
string n = "dog";
SwapString(m, n);
Console.WriteLine("m is " + m);//m is still cat
Console.WriteLine("n is " + n);//n is still dog
Point pnt1 = new Point(2,3);
Point pnt2 = new Point(20,30);
SwapObject(pnt1,pnt2);
Console.WriteLine("X: " + pnt1.x + " Y:" + pnt1.y); //x is 5, y
is 6
Console.WriteLine("X: " + pnt2.x + " Y: " + pnt2.y); //x is 20,
y is 30
}
static void SwapString(string s1,string s2)
{
s1 = "mouse";
string temp;
temp = s1;
s1 = s2;
s2 = temp;
}
static void SwapObject(Point arg1, Point arg2)
{
arg1.x = 5;
arg1.y = 6;
Point temp = arg1;
arg1 = arg2;
arg2 = temp;
}
class Point
{
public int x;
public int y;
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
}
有点疑问, 如果说string 在c#里面是reference type的话,为什么我下面的例子中m
is still cate , but not mouse.
static void Main(string[] args)
{
string m = "cat";
string n = "dog";
SwapString(m, n);
Console.WriteLine("m is " + m);//m is still cat
Console.WriteLine("n is " + n);//n is still dog
Point pnt1 = new Point(2,3);
Point pnt2 = new Point(20,30);
SwapObject(pnt1,pnt2);
Console.WriteLine("X: " + pnt1.x + " Y:" + pnt1.y); //x is 5, y
is 6
Console.WriteLine("X: " + pnt2.x + " Y: " + pnt2.y); //x is 20,
y is 30
}
static void SwapString(string s1,string s2)
{
s1 = "mouse";
string temp;
temp = s1;
s1 = s2;
s2 = temp;
}
static void SwapObject(Point arg1, Point arg2)
{
arg1.x = 5;
arg1.y = 6;
Point temp = arg1;
arg1 = arg2;
arg2 = temp;
}
class Point
{
public int x;
public int y;
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
}