c# 类 对象 属性 构造方法 理解

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 复习
{
    class Person
    {

        // 字段 属性 方法 构造函数
        //字段 存储数据
        //属性保护字段  对字段的取值和设值取值 
        //方法 描述对象的行为
        //构造函数 初始化对象() 
        //类中的成员如果不加修饰符都是private

        // _name 字段 
        string _name;
        // 属性的本质就是两个方法
        public string Name//属性
        {
            get { return _name; }//打印对象的时候使用的get方法
            set { if (value != "孙权")
                {
                    value = "孙权";
                }


                _name = value; }//给对象赋值的时候使用的set方法

        }
        //_age 字段
        int _age;
        public int Age
        {
            get {if (_age < 0 || _age > 100)// get用来判断字段
                {
                    return _age = 0;
                }

                return _age; }
            set { _age = value; }
        }
        //_gender字段
        char _gender;//属性
        public char Gender
        {
            get { if (_gender != '男'&& _gender !='女')
                {
                    return _gender = '男';
                }

                return _gender; }
            set { _gender = value; }

        }
        
       
        public void sayHello()//没有static称之为实例方法 或者叫非静态方法  
        {
            
            Console.WriteLine("{0},{1},{2}", this.Name, this.Age, this.Gender);//1 this:当前类的对象
        }

        public static int _id;
        
        //静态方法和非静态方法在调用上的区别: 如果是静态成员 类名.方法名
        public static void sayHellotwo()//静态方法  只能访问静态成员 不能访问非静态成员。
        {
            
            Console.WriteLine("调用静态方法");
        }

        //构造函数 没有返回值  void也没有
        // 构造函数的名称和类名一样
        public Person(string name, int age, char gender)
        {
            this.Name = name;
            this.Age = age;
            this.Gender = gender;
         
        }

        //用此构造函数调用全参的构造函数  
        //构造函数重载
        public Person(string name, char gender):this(name,0,gender)//2 this 调用自己的构造函数
        {
        }
       
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 复习
{
    class Program
    {
        static void Main(string[] args)
        {
            //类就是一个模子

            //  方法 描述对象的行为
            //构造方法 :初始化对象(给每个属性依次赋值)
            Person zsPerson = new Person("张珊",180,'n');// new的作用 1 在内存中开辟一段空间  2 在开辟的空间中创建对象 3调用对象的构造函数
            
            //非静态方法调用方式 :对象名.方法名
            zsPerson.sayHello();
            //静态方法调用方式:类名.方法名 
            Person.sayHellotwo();


        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值