Unity C# Basics Review 14 - Encapsulation (P239-244)

private: private members, which can only be accessed inside the class

public: public members, completely public, no access restrictions

protected: protected members, accessible within the class and inherited classes

internal: accessible within the current assembly. Assembly: exe\dll

internal protected: the union of internal and protected , all classes in the same assembly, and subclasses in all assemblies

The combination of behavior (method) and fields (data)

Meaning: A mechanism that combines fields (data members) and behaviors (code members)

Purpose:

1. Control the scope of object status

2. Strengthen the inline (linkage) nature of the object itself

3. Enhance the security of object use

Package diagram

​​​​​​​

Basic requirements for packaging:

Specific bounds: all internal changes are restricted to this bound ({ } of class definition)

Specific access rights: protected internal implementation details (private members) cannot be accessed or modified outside the object

There is an external interface ( method ): this object uses it to relate to other objects (public members)

For example: bank’s money withdrawal plan, etc.

namespace ConsoleApp1
{
    class Hero
    {
        //血量
        int hp;
        //性别
        char gender;
        //状态:true:活着  false:挂了
        bool state;
        

        public Hero(int hp)
        {
            this.hp = hp;
            this.state = true;
        }
        /// <summary>
        /// 受到伤害
        /// </summary>
        /// <param name="hurt"> 被伤害的数值</param>
        public void BeHurt(int hurt)
        {
            if (hurt < 0)
            {
                return;
            }
            this.hp = this.hp - hurt < 0 ? 0 : this.hp - hurt;

            if (this.hp == 0)
            {
                this.state = false;
            }
        }
        /// <summary>
        /// 获取当前英雄血量值
        /// </summary>
        /// <returns></returns>
        public int GetHp()
        {
            return hp;
        }

        public void SetGender(char gender)
        {
            if (gender == '男' || gender == '女')
            {
                this.gender = gender;
                return;
            }
            Console.WriteLine("性别必须为男或者女!");
            this.gender = '男';
        }
        public char GetGender()
        {
            return this.gender;
        }
        public bool GetState()
        {
            return this.state;
        }

        public void Attact()
        {
            if (this.state)
            {
                Console.WriteLine("普通攻击!");
            }
            else
            {
                Console.WriteLine("你已经阵亡,请等待复活");
            }
        }
    }
}
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            TestHero();
        }
        public static void TestHero()
        {
            Hero h = new Hero(1800);
            h.BeHurt(1000);
            Console.WriteLine(h.GetHp());

            h.SetGender('X');
            Console.WriteLine(h.GetGender());

            while (h.GetState())
            {
                h.Attact();
                h.BeHurt(500);
            }
        }
    }
}

The pattern shown above is called encapsulation, and there is linkage within the class.

Example: Write about a student category, grades and whether he or she failed the class

namespace Student
{
    class Student
    {
        //0-100
        int score;
        //false:不挂科 true:挂科
        bool over;

        public void SetScore(int score)
        {
            if (score < 0 || score > 100)
            {
                Console.WriteLine("成绩无效!");
                return;
            }
            this.score = score;
            //做字段了联动
            over = this.score < 60;
        }
        public int GetScore()
        {
            return this.score;
        }

        public bool GetOver()
        {
            return this.over;
        }
    }
}
namespace Student
{
    class Program
    {
        static void Main(string[] args)
        {
            TestStudent();
        }
        public static void TestStudent()
        {
            Student s = new Student();
            s.SetScore(1000);
            Console.WriteLine(s.GetOver() ? "挂了" : "没挂");
        }
    }
}

Encapsulated security

Give an example: User interface of the user

namespace User
{
    class User
    {
        String name;  //名字只能看,不能改,需要封装
        int password;  //应该可以改也可以拿

        int key = 171816;   //加密key

        public string GetName()
        {
            return this.name;
        }
        public void SetPassword(int password)
        {
            this.password = password ^ key ;
        }

        public int GetPassword()
        {
            return this.password;
        }
        public User()
        {

        }

        public User(string name, int password)
        {
            this.name = name;
            this.SetPassword(password);
        }

        public bool Login(int password)
        {
            if (this.password == (password ^ key))
            {
                return true;
            }
            return false;
        }
    }

}
namespace User
{
    class Program
    {
        static void Main(string[] args)
        {
            TestUser();
        }
        public static void TestUser()
        {
            Console.WriteLine("注册密码:");
            User user = new User("admin", int.Parse(Console.ReadLine()));
            Console.WriteLine(user.GetPassword());

            Console.WriteLine("验证密码");
            bool login = user.Login(int.Parse(Console.ReadLine()));
            Console.WriteLine(login);
        }
    }
}

Property encapsulation

Definition of attributes: attributes represent set and get methods

Guess you like

Origin blog.csdn.net/weixin_46711336/article/details/123062148