日期:2014-05-17  浏览次数:20842 次

string引用传递问题
请教各位,string在C#中是一个class,那么string  str
定义的字符串变量是引用类型么?  如果是的话,那也就是说,调用方法gaibian(string zifuchuan)来传递str的时候,str的值也会变,这样对么。
c# string class

------解决方案--------------------
string 是引用类型。

class Person{
   public string Name{get;set;}
   public int Age{get;set;}
}
public static void main(){
    Person tom = new Person();
    tom.Name = "Tom";
    tom.Age = 12;
    ChagePersonName(tom);
    Console.Write(tom.Name);
    tom.Name = "Tom";
    ChangePerson(tom);
    Console.Write(tom.Name);
}
public static void ChangePersonName(Person person){
    person.Name = "Jarry"; //这里通过person引用修改的person的属性值
}
public static void ChangePerson(Person person){
    person = new Person();//这里直接将参数指向了另一个对象,而前面的tom仍然指向原来的对象。
    person.Name="Jarry";//这里修改的是新对象的Name属性。
    person.Age = 32;
}

public static void changeString(string s){
    s = "aaa"; //这里将参数地址指向了另一个字符串,而实参仍然指向原来的字符串。
}
 
------解决方案--------------------
string 是引用类型。
传参数的时候传的是地址,但是,在方法里给string参数赋值时,会重新为参数分配地址。
所以不能改变实参的值。
除非用ref声明。。
            string s = "aaa";
            Console.WriteLine("Before call ModifyString : s = " +s);
            ModifyString(s);
            Console.WriteLine("After call ModifyString : s = " + s);
            Console.ReadLine();
        }

        static void ModifyString(string str)
        {
            str = "bbb";
        }

/// Result:
///Before call ModifyString : s = aaa
///After call ModifyString : s = aaa

        static void Main(string[] args)
        {
            string s = "aaa";
            Console.WriteLine("Before call ModifyString : s = " +s);
            ModifyString(ref s);
            Console.WriteLine("After call ModifyString : s = " + s);