C#之对象的引用与构造函数

对象的引用:

定义“person”类,设置属性:年龄。
namespace 对象的引用
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 10;
            int j = i;
            
            i++;
            Console.WriteLine(j);

            //int,datetime,bool,char等类型都属于值类型(ValueType)
            //赋值的时候是传递拷贝
            

             //普通的对象是引用类型,赋值的时候是传递引用
            person p1 = new person(20);
            person p2 = p1;
            
            p1.Age++;
            Console.WriteLine(p2.Age);

            Console.ReadKey();

        }
    }
    class person
    {
        public int Age
        {
            get;
            set;
        }
        public person(int age)     //带参数的构造函数
        {
            this.Age = age;
        }
    }
}

构造函数:

定义“person”类,设置属性:姓名,年龄。

设置不带参数的构造函数

设置带名字的构造函数

设置带年龄的构造函数

namespace 构造函数
{
    class Program
    {
        static void Main(string[] args)
        {
            person p1 = new person();
            person p2= new person( "小白");     //传递函数参数
            person p3 = new person(20, "大黄");

            Console.WriteLine("名字是{0},年龄是{1}", p1.name, p1.age);
            Console.WriteLine("名字是{0},年龄是{1}", p2.name, p2.age);
            Console.WriteLine("名字是{0},年龄是{1}", p3.name, p3.age);
            Console.ReadKey();
        }
    }
    class person
    {
        public string name { set; get; }
        public int age { set; get; }
        public person()       //默认不带参数的构造函数
        {
             name = "不知道";
             age = 0;
        }
           
        public person(string name)    //带参数的构造函数
        {
          this.name = name;
           
        }
        public person(int age,string name)     //重载的构造函数
        {
            this.name = name;
            this.age = age;
        }
    }
}
"小白");     //传递函数参数
            person p3 = new person(20, "大黄");

            Console.WriteLine("名字是{0},年龄是{1}", p1.name, p1.age);
            Console.WriteLine("名字是{0},年龄是{1}", p2.name, p2.age);
            Console.WriteLine("名字是{0},年龄是{1}", p3.name, p3.age);
            Console.ReadKey();
        }
    }
    class person
    {
        public string name { set; get; }
        public int age { set; get; }
        public person()       //默认不带参数的构造函数
        {
             name = "不知道";
             age = 0;
        }
           
        public person(string name)    //带参数的构造函数
        {
          this.name = name;
           
        }
        public person(int age,string name)     //重载的构造函数
        {
            this.name = name;
            this.age = age;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_42200934/article/details/81065674
今日推荐