一个很小的C#程序问题
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int x = 66;
int y = 99;
Swap(x,y);
Console.WriteLine("swap x/y is {0} , {1}", x, y);
Console.ReadLine();
}
static void Swap(int a ,int b)
{
int m, n, tmp;
m = a;
n = b;
Console.WriteLine("In swap methord (before) m is : ", m);
Console.WriteLine("In swap methord (before) n is : ", n);
// int temp = a;
// a = b;
// b = temp;
tmp = m;
m = n;
n = tmp;
Console.WriteLine("In swap methord (after) m is : ", m);
Console.WriteLine("In swap methord (after) n is : ", n);
}
}
}
这程序的结果 是
In swap methord (before) m is :
In swap methord (before) n is :
In swap methord (after) m is
In swap methord (after) n is
swap x/y is 66 99
请问下这是为什么 Swap静态方法是调用了
但是参数没有传进去?
本来我直接用了形参
// int temp = a;
// a = b;
// b = temp;
但是不行,后来方法里又弄了2个参数 还是不行
请问这是为什么? 展开
你的错误在于
没搞清楚int类型是值类型,并非引用类型,
所以int,Swap方法中的a,b;接收的是外部x,y的值
并非是地址,你在方法中交换的只是a,b,但x,y并没有交换
所以要在定义的Swap方法中参数前 加 ref ,reference的缩写 ,即引用
代码如下
static void Main(string[] args)
{
int x = 66;
int y = 99;Swap(ref x, ref y);
Console.WriteLine("swap x/y is {0} , {1}", x, y);Console.ReadLine();
}static void Swap(ref int a, ref int b)
{
int tmp;
tmp = a;
a = b;
b = tmp;
}
不是参数没有传进去,而是没有真的交换,你传进去的是值是交换了,但是那只是主方法变量x,y的副本,不是x,y本身。修改方法是将方法的参数改成引用
static void Swap(int & a ,int & b)
另外,如【抽插小旋风|六级】所说,你的Swap里面的WriteLine用的也不对,正确代码如下:
static void Swap(int & a ,int & b)
{
int tmp;
Console.WriteLine("In swap methord (before) a is :{0}", a);
Console.WriteLine("In swap methord (before) b is :{0}", b);
tmp = a;
a = b;
b = tmp;
Console.WriteLine("In swap methord (before) a is :{0}", a);
Console.WriteLine("In swap methord (before) b is :{0}", b);
}
Console.WriteLine("In swap methord (before) m is : {0}", m);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int x = 66;
int y = 99;
Swap(x, y);
Console.WriteLine("swap x/y is {0} , {1}", x, y);
Console.ReadLine();
}
static void Swap(int a, int b)
{
int m, n, tmp;
m = a;
n = b;
Console.WriteLine("In swap methord (before) m is {0}: ", m);
Console.WriteLine("In swap methord (before) n is {0}: ", n);
// int temp = a;
// a = b;
// b = temp;
tmp = m;
m = n;
n = tmp;
Console.WriteLine("In swap methord (after) m is: {0}", m);
Console.WriteLine("In swap methord (after) n is :{0} ", n);
}
}
}
变量的生命周期问题,在Swap(int a, int b)方法生命周期内tmp变量是可用的,到了主函数内tmp对主函数是不可用的,又怎么会改变a,b的值嘞?希望你多看看变量的生命周期