解析C#语言代码?谢谢啦。

来源:百度知道 编辑:UC知道 时间:2024/05/28 09:08:21
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication3
{
public class Foo
{
public void Modify(int n)
{
n = 100;
}
}
class Program
{
static void Main(string[] args)
{
int x = 100;
Foo f = new Foo();
Console.WriteLine("x before modify :"+x );
f.Modify(x);
Console.WriteLine("x after modify :"+x);
Console.ReadLine();
}
}
}
具体就是X的值为何都是一样的。

namespace ConsoleApplication3
{
public class Foo
{
public void Modify(int n) //更新方法
{
n = 100;//给参数N 赋值为100
}
}
class Program
{
static void Main(string[] args)
{
int x = 100; //定义X 为100
Foo f = new Foo(); //使用 FOO类
Console.WriteLine("x before modify :"+x ); //输出X更新前的值
f.Modify(x); // 调用 FOOl类的更新方法 给 X=100传进去了

Console.WriteLine("x after modify :"+x);//更新后的X 因为两次都是100 =、=
Console.ReadLine();
}
}
}

这个和n的作用范围有关,具体自己体会。
你改成
public void Modify(int &n)//这个不一定行,因为这是c++里的方法,到c#我就没试过了
{
n = 100;
}

我不明白为什么不一样?

你形参又不是传址的方式..即便是传址,也没改变x的值

C#用ref... 补充楼上

int x = 100;
你把这里这个x的值换一个非100的值,试试
应该输出的两个值就不一样了