黑马程序员技术交流社区

标题: c#面向对象编程—对象的引用 [打印本页]

作者: 小天    时间: 2013-8-2 02:05
标题: c#面向对象编程—对象的引用
c#面向对象编程—对象的引用:易出错的地方
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 对象的引用
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 10;
            int j = i;
            i++;
            Console.WriteLine(j);//输出10
            //int、datetime、bool、char等类型属于值类型(ValueType),赋值的时候传递的拷贝
        
            //普通对象则是引用类型,赋值的时候传递的是引用
            Person p1 = new Person(10);
            Person p2=p1;//指向的同一个对象
            p1.Age++;
            Console.WriteLine(p2.Age);

            IncAge(p2);//传递给函数也是引用传递的
            Console.WriteLine(p2.Age);
            Console.ReadKey();
        }
        static void IncAge(Person p)
        {
            p.Age++;
        }
    }
    class Person
    {
        public int Age { set; get; }//声明一个属性Age
        public Person(int age)//声明了一个构造函数
        {
            this.Age = age;
        }
    }
}


作者: 许庭洲    时间: 2013-8-2 06:13
值得学习ing!




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2