9. C#Structural Class Properties

Posted by Yola on Sat, 05 Feb 2022 18:03:55 +0100

1. Use of structure

Structures: Declare several different types of variables at once

Location of declaration: Declares the structure below the namespace, outside the class, identifying the namespace under which all classes can use the structure

Initializing structure members can be done in two ways
One is to use a parameterized constructor, using the new keyword
Second, access members separately after declaring the structure (error will occur if only some fields are copied)

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

namespace _1_Use of structure
{
    //It is best to declare the structure at this location, since all classes can be accessed
    public struct Clerk   //Declaration of constructor
    {
        //Declare Variables
        public string name;
        public int age;
        public string department;
        public char gender;
    }
    class Program
    {
        //If a structure is declared at this location, only the current class or its inherited class can be used
        static void Main(string[] args)
        {
            //Use of construction methods
            Clerk zs = new Clerk();
            zs.name = "Zhang San";
            zs.age = 25;
            zs.department = "Purchasing Department";
            zs.gender = 'male';
            Console.WriteLine(zs.name+"\t"+zs.age + "\t" + zs.department + "\t" + zs.gender);
            Console.ReadKey();
        }
    }
}

2. Enumeration

If you want a fixed set of values, use enumeration

Declarations
[public] enum enumeration name
{
Value 1
Value 2
Value 3
......
}
Declare Location: Declare the enumeration below the namespace and outside the class to indicate that all classes in the namespace can use the enumeration
Enumeration is a variable type, int doubule string decimal
Only enumeration declarations, assignments, and usage are different from those of common variable types, by ** "enumeration name." ** Method reference
By default, each value is automatically assigned an integer type starting at 0 in the order defined.

2.1 Type Conversion

Enumeration converts to int, and to get the value of the enumeration, simply slow down to sting type.
Enumeration and string convert to each other
Converting a string to an enumeration type requires the following line of code:

  • Enum. Parse (typeof), String to Convert
  • If the converted string is a number, no exceptions will be thrown even if none of the enumerations are present
  • If the converted string is text, if it is not in the enumeration, an exception will be thrown
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _2_enumeration
{
    //An enumeration is declared here, which acts like a structure, so the location is the same, but at the same time, the enumeration can also be called in a structure
    public enum Gender
    {
        male,
        female
    }
    public enum department
    {
        //Each value is automatically assigned an integer type starting at 0 in the order defined.
        Human Resources Department,   //0
        Finance Department,       //1
        Test Department,       //2
        R&D Department,        //3
        Product Department=10,      //It is assumed that an integer has been specified instead of the default order
        President's Department

    }
    class Program
    {
        static void Main(string[] args)
        {
            //Enumerated calls
            Gender zsgender = Gender.male;
            Console.WriteLine(zsgender);
            Console.WriteLine((int)zsgender);          //Convert Enumeration to Integer
            Console.WriteLine(zsgender.ToString());    //Convert Enumeration to String
            department zsdepartment = department.Finance Department;
            Console.WriteLine(zsdepartment);
            Console.WriteLine((int)zsdepartment);   //Output here is 3,
            department lsdepartment = department.Product Department;
            Console.WriteLine(lsdepartment);
            Console.WriteLine((int)lsdepartment);   //The output here is 10,
            int myint = 10;
            Console.WriteLine((department)myint);  //Convert integer to enumeration, where output is product department

            //Converts an enumeration to a string, not a string, but only a string. Tostring or convert.Tostring()
            Console.WriteLine(lsdepartment);  //On output, the output statement has automatically converted the enumeration type to a string line
            Console.WriteLine(lsdepartment.ToString());
            Console.WriteLine(Convert.ToString(lsdepartment));

            //Convert string to enumeration value
            string mystr = "Product Department";
            Console.WriteLine((department)Enum.Parse(typeof(department), mystr));
            string mystr2 = "Product Department";
            Console.WriteLine((department)Enum.Parse(typeof(department), mystr2));  //Exceptions will be reported here
            Console.ReadKey();
        }
    }
}

3. Object Oriented Programming

  • Process Oriented: It is also the way for us to do things from start to finish, one step at a time, what we do first, then what we do afterwards, all the way to the end.
  • Object Oriented: Divides a project (or thing) into smaller projects (or smaller parts), each of which is responsible for one aspect of functionality and, ultimately, makes up a whole. This method is more suitable for multiple people.
  • Procedure Oriented is the process of analyzing and solving a problem, then using functions to implement these steps step by step, then calling them one by one when they are used. Emphasis is on the action to accomplish this, closer to the way we think about things in our daily life
  • Object oriented, which divides the transaction that constitutes a problem into objects, is not created to complete a comparison of Europe, but to describe what happens to something in the process of solving the whole problem. It is intended to write generic code, enhance code reuse, and shield differences.

4. Relationship between Classes and Objects

  • In the real world we describe an object by describing its characteristics and behavior
  • We describe an object in code by describing its properties (characteristics) and methods (behavior). Objects must be visible, visible and palpable.
  • We further ledger these objects with the same attributes and methods to abstract the concept of class
  • A class is a template that determines the properties and methods an object should have.
  • Objects are rebuilt from classes. Class does not occupy memory, object station memory. Objects are independent. Operating on one of them will not affect another object of the same class.

5. Declarations of classes

  • A class is a data structure that can contain data members (constants and fields) function members (methods, attributes, time, indexers, operators, instance constructors, static constructors, destructors) and nested types.
  • All types in C#are classes, and all statements except for the referenced namespace must be within classes (or structures), and no statements outside classes exist. Therefore, classes are the core and basic building blocks of C#language. Include a Program class in the default code

Declaration of class 5.1

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

namespace _5_Declaration of class
{
    //Declare a class
    class clerk
    {

    }
    
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}

Classes are generally declared without the above method: (shortcut shift+alt+c)

Assignment of Class 5.2

Class:

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

namespace _5_Declaration of class
{
    //enumeration
    public enum Gender
    {
        male,
        female
    }
    class clerk
    {
        //Methods can store fields, attributes, and methods

        //Variables declared in a class are called fields
        //Variables can only hold one value, fields can hold multiple values, and fields are used to store data.
        //Naming specifications for fields: _ CameCase (Underline is not required)
        public string _name;
        public Gender _gender;
        public int _age;
        public string _department;
        public int _workYear;

        //Static methods can only call static members, and non-static methods can call any member
        public  void Write()
        {

            Console.WriteLine("My name is{0},I am{1}Life, I{2}Aged, I am{3}In office, I work{4}year", _name, _gender, _age, _department, _workYear);
        }
        public void Write2()
        {            //this represents the instantiated object

            Console.WriteLine("My name is{0},I am{1}Life, I{2}Aged, I am{3}In office, I work{4}year", this._name, this._gender, this._age, this._department, this._workYear);
        }

    }
}

Main method

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

namespace _5_Declaration of class
{
    //Declare a class
    class clerk1
    {

    }
    
    class Program
    {
        static void Main(string[] args)
        {
            //Instantiating a class means assigning it to an object
            clerk zsClerk = new clerk();
            
            zsClerk._name = "Zhang San";
            zsClerk._gender = Gender.male;
            zsClerk._department = "Department of Human Resources";
            zsClerk._age = 40;
            zsClerk._workYear = 25;
            string mystring = "Zhang San";

            //Invoke non-static methods
            zsClerk.Write();
            //Reinitialize
            clerk lsClerk = new clerk();
            lsClerk._name = "Li Si";
            lsClerk._age = 30;
            lsClerk._gender = Gender.female;
            lsClerk._workYear = 3;
            lsClerk._department = "Finance Department";
            mystring = "Li Si";
            lsClerk.Write();
            lsClerk.Write2();  //This command line describes the this keyword

            //The following output shows that a field can hold multiple values and a variable can hold only one value
            Console.WriteLine(zsClerk._name);
            Console.WriteLine(lsClerk._name);
            Console.WriteLine(mystring);
            Console.WriteLine(mystring);



            Console.ReadKey();

        }
    }
}

6. Use of attributes

  • Enables a programmer to create a new kind of declarative information called attributes. Attributes are abstractions that show the characteristics of entities in the world and provide common access to custom types of annotation information. Attributes enable an open way of thinking
  • Role of attributes: Protect fields, restrict field values and copy
  • Description: Attributes are often declared below fields and fields are privateized;
  • Attribute format:
    public [corresponding field type] attribute name
    {
    get {return _name}
    set{ _name=_value;}
    }
  • With attributes, we often access fields through attributes (for example, attributes are men, external affairs, and fields are women's internal affairs).
  • Attributes are usually declared public and fields are declared private ()
  • Fields in external access classes are implemented through attributes
  • In the property's Set and Get methods full man property declarations, we usually refer to get and set as accessors. Get property accessor returns property value, Set property accessor assigns new value
  • There are four types of attributes
    • Read and write with get and set
    • Read-only, contains get only
    • Write-only contains set only
    • Auto get; set;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _6_attribute
{
    class Clerk
    {
        //Members that can be stored in a class
        //Field: Use _ camelClass Naming Method
        //Attribute: PascalCase naming
        //Method
        private string _name;
        public string Name
        {
            //Automatic attributes, mainly for reservation, so that attributes can be qualified later
            get;
            set;
        }
        private char _gender;
        //With attributes, we tend to access fields through attributes
        //For example, attributes are men, responsible for external affairs, and fields are women's internal affairs
        //Attributes are usually declared public and fields are declared private ()
        //Fields in external access classes are implemented through attributes
        //Usually we refer to get and set as accessors
        //There are four types of attributes
       // 1)
        public char Gender
        {
            get //get can be used to restrict values_ age
            {
                if (_gender != 'male' || _gender != 'female') _gender = 'male';
                return _gender;
            }
            set  //set can be used to qualify value s for assignments
            { _gender = value; }   //value is a variable built into an attribute and cannot be renamed artificially
        }
        private int _age;
        public int Age
        {
            
            get
            {
                return _age;
            }
            set
            {
                if (value < 0 || value > 120) value = 0;  // Limited Assignment
                _age = value;

            }
        }
        private string _department;
        public string Department
        {
            get;
            set;
        }
        public int _workYear;
        public int WorkYear
        {
            get;
            set;
        }
        public void Wrte()
        {
            Console.WriteLine("My name is{0},I am{1}Life, I{2}Aged, I am{3}In office, I work{4}year", this.Name, this.Gender, this.Age, this.Department, this.WorkYear);

        }
    }
}

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

namespace _6_attribute
{
    class Program
    {
        static void Main(string[] args)
        {
            //Instantiate the class, assign values separately, and call its methods
            Clerk zsClerk = new Clerk();
            zsClerk.Name = "Zhang San";
            zsClerk.Age = 25;
            zsClerk.Department = "Department of Human Resources";
            zsClerk.WorkYear = 5;
            zsClerk.Gender = 'male';
            zsClerk.Wrte();
            Console.ReadKey();


        }
    }
}

8. Constructors and Destructors

Constructors and parsers in common: When writing code, if they are not provided, the compiler automatically adds them

8.1 Constructor

Constructor is a special method

 - The constructor does not return a value, even void Nor can it be written, it must public
 - The name of the constructor must be the same as the class name

Role: Helps US initialize objects (assign values to each property of the object once)

Constructors are executed when an object is created and can be overloaded
There will be a default parameterless constructor in the class, and when you write a new constructor, either parameterless or parameterless, the default parameterless constructor is overridden.

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

namespace _8_Constructors and Destructors
{
    public enum Gender
    {
        male,
        female
    }
    class Clerk
    {
        private string _name;
        public string Name
        {
            get;
            set;
        }
        private Gender _gender;
        public Gender Gender
        {
            get
            {
                return _gender;
            }

            set
            {
                _gender = value;
            }
        }
        private int _age;
        public int Age
        {
            get
            {
                return _age;
            }

            set
            {
                _age = value;
            }
        }
        private string _department;
        public string Department
        {
            get
            {
                return _department;
            }

            set
            {
                _department = value;
            }
        }
        private int _workYear;
        public int WorkYear
        {
            get
            {
                return _workYear;
            }

            set
            {
                _workYear = value;
            }
        }
        public void Write()
        {
            Console.WriteLine("My name is{0},I am{1}Life, I{2}Aged, I am{3}In office, I work{4}year", this.Name, this.Gender, this.Age, this.Department, this.WorkYear);

        }
        //Constructor
        public Clerk(string name, Gender gender, int age, string department, int workYear) 
        {
            this.Name = name;
            this.Age = age;
            this.Gender = gender;
            this.Department = department;
            this.WorkYear = workYear;
        }
        
        public Clerk(string name, Gender gender, int age) //Overloading Constructors
        {
            this.Name = name;
            this.Age = age;
            this.Gender = gender;
        }
    }
}

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

namespace _8_Constructors and Destructors
{
    class Program
    {
        static void Main(string[] args)
        {
            //Clerk zsClerk = new Clerk();
            //zsClerk.Name = "Zhang San";
            //zsClerk.Gender = Gender. Male;
            //zsClerk.Age = 30;
            //zsClerk.Department = Test Department;
            //zsClerk.WorkYear = 10;
            //zsClerk.Write();
            Clerk zsClerk = new Clerk("Zhang San",Gender.male,25,"Test Department",5);
            zsClerk.Write();
                Clerk lsClerk = new Clerk("Zhang San", Gender.male, 25);
            lsClerk.Write2();
            Console.ReadKey();
        }
    }
}

8.3 new keywords

  • Open up space in memory
  • Create objects in open space
  • Initialize the object and assign the attribute value of Jiang Brother

8.3 Destructor (Release Resources)

  • Destructors are method members that implement the destruction of an instance of a class. Destructors cannot have parameters, have no modifiers, and cannot be called. Destructors differ from constructors in purpose by prefixing destructors with a'~'prefix
  • Constructors and destructors are formally simpler functions in a class, but they are never as simple as they seem, so using them flexibly and correctly can help users better understand the memory mechanism of CLR and make better use of system resources.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _8_Constructors and Destructors
{
    public enum Gender
    {
        male,
        female
    }
    class Clerk
    {
        private string _name;
        public string Name
        {
            get;
            set;
        }
        private Gender _gender;
        public Gender Gender
        {
            get
            {
                return _gender;
            }

            set
            {
                _gender = value;
            }
        }
        private int _age;
        public int Age
        {
            get
            {
                return _age;
            }

            set
            {
                _age = value;
            }
        }
        private string _department;
        public string Department
        {
            get
            {
                return _department;
            }

            set
            {
                _department = value;
            }
        }
        private int _workYear;
        public int WorkYear
        {
            get
            {
                return _workYear;
            }

            set
            {
                _workYear = value;
            }
        }
        public void Write()
        {
            Console.WriteLine("My name is{0},I am{1}Life, I{2}Aged, I am{3}In office, I work{4}year", this.Name, this.Gender, this.Age, this.Department, this.WorkYear);

        }
        public void Write2()
        {
            Console.WriteLine("My name is{0},I am{1}Life, I{2}Age", this.Name, this.Gender, this.Age);

        }
        //Constructor
        public Clerk(string name, Gender gender, int age, string department, int workYear) 
        {
            this.Name = name;
            this.Age = age;
            this.Gender = gender;
            this.Department = department;
            this.WorkYear = workYear;
        }

        public Clerk(string name, Gender gender, int age) //Overloading Constructors
        {
            this.Name = name;
            this.Age = age;
            this.Gender = gender;
        }

        //If a destructor is not specified in the system, the compiler has GC to decide when to release the resource
        //Garage Collection
        ~Clerk()  //Destructor
        {
            Console.WriteLine("I'm a destructor, see when I call it");
            //The destructor is called when the current class is used up
        }
    }
}

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

namespace _8_Constructors and Destructors
{
    class Program
    {
        static void Main(string[] args)
        {
            //Clerk zsClerk = new Clerk();
            //zsClerk.Name = "Zhang San";
            //zsClerk.Gender = Gender. Male;
            //zsClerk.Age = 30;
            //zsClerk.Department = Test Department;
            //zsClerk.WorkYear = 10;
            //zsClerk.Write();
            Clerk zsClerk = new Clerk("Zhang San",Gender.male,25,"Test Department",5);
            zsClerk.Write();
            Clerk lsClerk = new Clerk("Zhang San", Gender.male, 25);
            lsClerk.Write2();
            Console.ReadKey();
        }
    }
}

10. Inheritance of Classes

The three basic features of object-oriented are encapsulation, inheritance and polymorphism
Example: Three classes:
Clerk: _ Name, Name;_ Department, Department can be declared as a parent class
Sales:_ Name, Name;_ Department, Department, _ SalesTarget, SalesTarget declares as a subclass, inherits Clerk
Technical Support:_ Name, Name;_ Department, department;_ SatisfactionRate, declared as a subclass, inherits Clerk

  • Inheritance: For a class, what is called inheritance is that the subclass contains the data structure and behavior of the parent class, including fields, attributes, methods, and events
  • Although these definitions are not included in the definition of the subclass itself, you can still use these parent class members.
  • In the inheritance of a class, the inherited class is called the base class or the parent class, and the inherited class is called the derived class or the subclass
  • When a class derives from another class, the derived class naturally has base class data members, attribute members, method members, etc. The code for these members in the base class definition no longer needs to be overridden in the derived class definition. In the definition of a derived class, all you need to do is write all the code that lays out in the base class definition.
  • Purpose:
    • Improved code reuse
    • Improving the efficiency of program design
    • Provides free space for writing code for specific needs in program design, which improves the scalability of existing program design results
  • Class Sinking Attention Rule:
    • Single root (can inherit only one class)
    • Transitivity (see class diagram)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _10_Class Inheritance
{
    class clerk
    {

        private string _name;
        //Private is private, so subclasses are not allowed to access it
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }
        private string _department;
        public string Department
        {
            get
            {
                return _department;
            }

            set
            {
                _department = value;
            }
        }
        public void CSayHello()
        {
            Console.WriteLine("Hello I am{0}Of{1}",this.Name, this.Department);
        }
      

    }
}

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

namespace _10_Class Inheritance
{
    //Inherit Clerk Class
    class sales:clerk
    {
        private int _salesTarget;

        public int SalesTarget
        {
            get
            {
                return _salesTarget;
            }

            set
            {
                _salesTarget = value;
            }
        }
        public void SSayHello()
        {
            Console.WriteLine("Hello, I am{0}Of{1},My sales target is{2}",this.Department, this.Name, this.SalesTarget);
        }
    }
}

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

namespace _10_Class Inheritance
{
    class TechnicalSupport:clerk
    {
        private double _statisfactionRate;

        public double StatisfactionRate
        {
            get
            {
                return _statisfactionRate;
            }

            set
            {
                _statisfactionRate = value;
            }
        }
        public void TSSayHello()
        {
            Console.WriteLine("Hello, I am{0}Of{1},My service satisfaction rate is{2}",this.Name,this.Department,this.StatisfactionRate);
        }
    }
}

 - Derived class defines a member with the same name as the base class, overriding the base class member

 - Derived classes naturally inherit members of classes, but cannot inherit constructor members of base classes. There are two ways to solve this problem:
	 - Define a parameterless constructor in the parent class, or define your own constructor in the child class
	 - Use keywords: base()



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

namespace _10_Class Inheritance
{
    class Program
    {
        static void Main(string[] args)
        {
            clerk zsclerk = new clerk("Zhang San", "Ministry of Personnel");


            sales zssales = new sales("Zhang San", "Ministry of Personnel",2500);

        }
    }
}

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

namespace _10_Class Inheritance
{
    class clerk
    {

        private string _name;
        //Private is private, so subclasses are not allowed to access it
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }
        private string _department;
        public string Department
        {
            get
            {
                return _department;
            }

            set
            {
                _department = value;
            }
        }
        public void CSayHello()
        {
            Console.WriteLine("Hello I am{0}Of{1}",this.Name, this.Department);
        }

        //Constructor
        //Constructors in the parent cannot be inherited in a subclass, but parameterless constructors in the parent are called by default
        //Two method subclasses inherit the constructor of the parent class
        //1) Write another parameterless constructor in the parent class, rewrite the constructor once in each subclass and assign values to each field
        //2) Use keywords: base()


        public clerk(string name, string department)
        {
            this.Name = name;
            this.Department = department;
        }
        public clerk() { }

      

    }
}

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

namespace _10_Class Inheritance
{
    //Inherit Clerk Class
    class sales:clerk
    {

        private  string _name;
        //The new keyword can be used to hide members of the same name from the base class
        //new instantiation object
        public new string Name
        {
            get
            {
                return _name;
            }

            set
            {
                _name = value;
            }
        }

        private int _salesTarget;
       

        public int SalesTarget
        {
            get
            {
                return _salesTarget;
            }

            set
            {
                _salesTarget = value;
            }
        }
        public void SSayHello()
        {
            Console.WriteLine("Hello, I am{0}Of{1},My sales target is{2}",this.Department, this.Name, this.SalesTarget);
        }
        //Subclass constructor mode one
        //public sales(string name, string department, int salesTarget)
        //{
        //    this.Name = name;
        //    this.Department = department;
        //    this.SalesTarget = salesTarget;
        //}
        //Subclass constructor and
        public sales(string name, string department, int salesTarget):base(name,department)
        {
            this.SalesTarget = salesTarget;
        }
    }
}

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

namespace _10_Class Inheritance
{
    class TechnicalSupport : clerk
    {
        private double _statisfactionRate;

        public double StatisfactionRate
        {
            get
            {
                return _statisfactionRate;
            }

            set
            {
                _statisfactionRate = value;
            }
        }
        public void TSSayHello()
        {
            Console.WriteLine("Hello, I am{0}Of{1},My service satisfaction rate is{2}", this.Name, this.Department, this.StatisfactionRate);
        }

        public TechnicalSupport(string name, string department, double satisfactionRate) : base(name, department)
        {
            this.StatisfactionRate = satisfactionRate;
        }
    }
}

Sealing of Class 10.1

If the user wants a class not to be used as a base class, then the sealed keyword must be used for a long time
The only limitation is that abstract classes cannot be used as enclosed classes because the nature of abstract classes determines that they must be used as base classes.
The purpose of enclosing classes is to prevent unexpected derivation operations. Specifically, because the compiler determines that this class does not have any derived classes, virtual function member calls on enclosed class instances can be converted to non-virtual calls.

11. Class Encapsulation

  • Encapsulation is the first step in object-oriented programming. Encapsulation is the collection of data or functions in a single unit (we call them classes). Encapsulated objects are often referred to as abstract data types
  • Meaning: The meaning of encapsulation is to prevent code (data) from being inadvertently destroyed by us. Prevent access to implementation details.
  • We only provide methods to use classes, and callers don't have to know how to handle the related data inside the class
  • C#usually encapsulates methods or other data members in a class.
  • Encapsulation is accomplished using access modifiers. An access modifier defines the scope and visibility of a class member
  • Access modifiers:
    • public
    • private
    • protected
    • internal
    • protected internal

11.1 Access Modifier

  • public: public, allowing a class to expose its member variables and functions to other functions and objects. Any shared member can be accessed by an external class
  • Private: can only be accessed inside the current class, the default access modifier for class members. Allows a class to hide its member variables and functions from other functions and objects. Only functions in the same class can access their private members. Even an instance of a class cannot access its private members
  • protected: protected, accessible only within and within the current class, allowing subclasses to access member variables and member functions of its base class. Masking helps to achieve inheritance.
  • Internal can only be accessed in the current project. Internal and public have the same permissions in the same project. Allows a class to expose its member variables and functions to other functions and objects in the current program. In other words, any member with an internal access modifier can be accessed by any class or method defined within the application defined by that member.
  • Protected internal: Allows a class to hide its member variables and member functions from other class objects and functions that are unexpected for subclasses within a unified application. This is also used to implement inheritance
  • There are only two access modifiers that can modify a class: public, internal
  • Access properties are inconsistent, and access permissions of subclasses cannot be higher than those of parent classes

12. Class Polymorphism

  • In the inheritance of classes, C#allows declarations of methods with the same name in the base and derived classes, and methods with the same name can have different codes, that is, different implementations can be used in the same functions of the base and derived classes, thus providing multiple ways to solve the same problem
  • Polymorphism means that when a program is running, a statement that calls a method can be executed in different ways depending on the type of derived class object.

Implementation of Class 12.1 Polymorphism

  • Virtual method: Mark the method of the parent class as virtual, using the keyword virtual, which can be overridden in the subclass (using the keyword override)

  • Abstract classes and methods: If we don't need to create objects with a parent class, it exists only as inheritance from a common child class. You can write parent classes as abstract classes, parent methods as abstract methods, and methods in subclasses as override s

  • Interface implementation
    Whether we choose to implement polymorphism using virtual methods or abstract class abstract methods depends on whether we need to use objects instantiated by base classes

    • Abstract Class: No need to instantiate objects using base classes
    • Virtual method: need to instantiate object using base class

12.2 Virtual Method Implementation Polymorphism

main method call

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

namespace _13 Class Polymorphism
{
    class Program
    {
        static void Main(string[] args)
        {
            //Virtual Method Implementation Polymorphism
            clerk myclerk = new clerk();
            projectManager mypm = new projectManager();

            clerk[] clerks = { myclerk, mypm };
            foreach (clerk outclerk in clerks)
            {
                outclerk.WorkPlan();  
                
            }

            foreach (clerk outclerk in clerks)
            {
                outclerk.WorkPlan2();

            }

            Console.ReadKey();
        }
    }
}

Base Classes and Virtual Methods

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

namespace _13 Class Polymorphism
{
    class clerk
    {
        public void WorkPlan()
        {
            Console.WriteLine("I'm an employee and I need a work plan");
        }
        public virtual void WorkPlan2()
        {
            Console.WriteLine("Employee's Work Plan under Virtual Method");
        }


    }
}

Derived Classes and Virtual Method Overrides

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

namespace _13 Class Polymorphism
{
    class projectManager:clerk
    {
        public new void WorkPlan()
        {
            Console.WriteLine("I'm a project manager and I need a work plan");
        }
        public override void WorkPlan2()
        {
            Console.WriteLine("Project Manager Work Plan under Virtual Method");
        }

    }
}

Abstract Class Abstract Method Implements Polymorphism

Main method

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

namespace _13 Class Polymorphism
{
    class Program
    {
        static void Main(string[] args)
        {
            //Abstract method implements polymorphism (abstract classes are not allowed to create instances)
            Drink myMilk = new Milk();
            Drink myTea = new Tea();
            Drink[] drinkArry = { myMilk, myTea };
            foreach (Drink outDrink in drinkArry) outDrink.drink();


            Console.ReadKey();
        }
    }
}

Base class (abstract class)

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

namespace _13 Class Polymorphism
{
    abstract class Drink  //abstract class
    {
        //Implemented in abstraction, class abstraction, method abstraction, and methods cannot have method body {}
        public abstract void drink();  //Abstract methods, abstract methods cannot contain method bodies
        //{
        //    Console.WriteLine("I am a drink and I can quench my thirst");
        //}
    }
}

Derived Class

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

namespace _13 Class Polymorphism
{
    class Milk:Drink
    {
        public override void drink()
        {
            Console.WriteLine("I'm milk, I can quench thirst");
        }
    }
}

Derived Class

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

namespace _13 Class Polymorphism
{
    class Tea:Drink
    {
        public override void drink()
        {
            Console.WriteLine("I'm a tea. I can quench my thirst");
        }
    }
}

summary

Structures are rarely used when using classes and objects

Topics: C# Class