处理参考类型

1 c# types reference

当引用变量可以通过引用传递时:

    class Example
    {
        public string str="Demo";

        public int[] intValues={1,3,4,5};

       public static void StrPassing(string someStr)
        {
            string otherStr="Changed!";
            someStr=otherStr;
        }

        public static void NumPassing(int[] a)
        {
            a[2] = 115;
        }

    }


       static void Main(string[] args)
        {
            Example ex = new Example();
            Example.StrPassing(ex.str);
            Example.NumPassing(ex.intValues);

            foreach (int i in ex.intValues)
            {
                Console.WriteLine(i);
            }

            Console.WriteLine(ex.str);
            Console.ReadLine();
        }
Run Code Online (Sandbox Code Playgroud)

intValues[2]被改变115为参考正在passed.But(演示)的字符串"海峡"的值不会更改为"改变了!"这是什么原因呢?我.可把它作为数组传递通过引用和其他引用类型按值传递?

Joe*_*oey 5

无论您传递给方法的是什么,因为参数是通过值传递的,对于引用类型,这意味着引用按值传递.因此,您无法将对象更改为另一个,但您可以确定地更改其内容(因为这不会更改实际引用,只会更改其他地方的内存).

由于与阵列的示例演示你把数组引用(但不改变它),并更改值数组中.这就像获取一些对象并更改属性值一样.你也可以在一个方法中做到这一点.

如果要更改字符串(.NET中的不可变对象),则需要求助于ref参数:

public static void StrPassing(ref string someStr)
{
    string otherStr="Changed!";
    someStr=otherStr;
}
Run Code Online (Sandbox Code Playgroud)

并称之为:

string foo = "foo";
StrPassing(ref foo);
Console.WriteLine(foo); // should print "Changed!"
Run Code Online (Sandbox Code Playgroud)

ref关键字可确保您的方法获取的实际参考字符串,可以改变它,而不是只是一个参考的副本.那么你可以用一个全新的替换对象.

回到你的阵列:你也很难将传递的数组更改为一个完全不同的数组:

public static void NumPassing(int[] a)
{
    a = new int[15];
}
Run Code Online (Sandbox Code Playgroud)

也不会工作,因为那时你会尝试将字符串更改为完全不同的字符串.