举个例子
int b=1;
static void example(ref b)
{
。。
}按照上面的步骤, 到第2行的时候,b是没有被赋值的!就是按照引用传递的意思,我不太明白,既然是引用的那个地址,那么,定义I int b=1的时候,此时这个b的地址跟下面ref b不是一个地址吗?

解决方案 »

  1.   

    static void example(ref b)
    这个b是参数b,跟上面的int b根本不是一码事。
      

  2.   


    class Program
    {
      
      static void example(ref b)
      {
        b = 2;
      }
      static void Main(string[] args)
      {
        int b = 1;
        example(ref b);
        Console.WriteLine(b); // 输出应该是2  
      }
    }
      

  3.   

    static void example(ref b)可以有这种写法么?不用带参数类型?
      

  4.   


    嗯,楼上的很细心,应该需要参数类型的,例如:
    static void example (ref int b)
      

  5.   

    ref int b是参数,需要调用example(ref int b)的时候才有意义的,
    和int b不是一回事啊
      

  6.   

    ref的意思是按引用传递。不知道你是否熟悉c++,比如:
    int a = 10, b = 20;
    void swap(int x, int y)
    {
        int temp = x;
        x = y;
        y = temp;
    }
    如果你简单的调用这个swap,比如:swap(a, b),那么你根本没办法交换这两个变量的值,因为x和y都是形参,在swap返回的时候,x和y都被释放了。
    但如果你是这样定义swap:
    void swap (int& x, int& y)
    {
        int temp = x;
        x = y;
        y = temp;
    }
    也就相当于x与a,y与b指向同一个内存地址,那么对x的操作也就相当于对a的操作。
    那么在C#里面,这种效果对于值类型是很明显的。具体哪些是值类型?楼主请参考CTS相关的文档。请参考下面的例子:    class Program
        {
            static void Test(ref int b)
            {
                b = 2;
            }        static void Main(string[] args)
            {
                int b = 1;
                Test(ref b);
                Console.WriteLine(b);
            }
        }此时的输出是2,也就是Test方法中的b与Main中的b指向同一个内存地址,那么对Test.b的操作也就是对Main.b的操作。你如果把程序改成:    class Program
        {
            static void Test(int b)
            {
                b = 2;
            }        static void Main(string[] args)
            {
                int b = 1;
                Test(b);
                Console.WriteLine(b);
            }
        }那么输出的还是1,因为Test.b不是Main.b的引用,也就是一个单独的形参。
    现在再看对于引用类型,会是什么效果:    class TestClass
        {
            public int b;
        }    class Program
        {
            static void Test(TestClass b)
            {
                b.b = 2;
            }        static void Main(string[] args)
            {
                TestClass b = new TestClass();
                b.b = 1;
                Test(b);
                Console.WriteLine(b.b);
            }
        }上面的代码,输出的是2,因为b是引用类型,加不加ref关键字都一样。
    这也就是12楼phy同志所描述的意思。