c#字符串值类型与引用类型比较示例


复制代码 代码如下:

classProgram
{
    staticvoid Main()

    {
        int a = 9;    //给变量a赋值为9
        int b = a;   //将a的副本给变量b
        b = 10;
        Console.WriteLine(string.Format("a={0},b={1}", a, b));
        Person ZS = newPerson();       //张三
        ZS.Age = 99;           //张三的年龄是99
        Person SM = ZS;        //三毛等于张三,即张三和三毛就是同一个人
        SM.Age = 100;      //三毛年龄变成100,张三也就变成了100
       Console.WriteLine(string.Format("A={0},B={1}", ZS.Age, SM.Age));
        Console.ReadKey();

    }

}
classPerson
{
    publicint Age { get; set; }
}

相同的结构,不同的结果。


证明string是引用类型

复制代码 代码如下:

using System;

classProgram
{
    staticvoid Main()
    {
        int n = 99;
        Console.WriteLine("Before:n={0}", n.GetHashCode());
        //此时获取到的哈希码值就是n的变量值
        GetInt(n);
        string s = "Hello";
        Console.WriteLine("Before:s={0}", s.GetHashCode());
        GetString(s);
        Console.ReadKey();
    }
    staticint GetInt(int n)
    {
        Console.WriteLine("After:m={0}", n.GetHashCode());
        //传过来的是变量值,说明这是值传递
        return n;
    }
    staticstring GetString(string s)
    {
        Console.WriteLine("After:s={0}", s.GetHashCode());
        //传过来的是地址而不"Hello",说明这时引用传递
        return s;
    }
}


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3