C# learning - use of classes

1, Define class

In order to make the program clearer and easier to use, object-oriented programming is used
Class is actually the template of objects. Each object contains data and provides methods to process and access data
Class defines what data and functions each object of a class (called an instance) can contain, mainly including data members and function members
Data members: fields,
Function members: Methods
Code example: first, create a class under the project, named Customer, which contains three fields and a function, and call it under the main function

Customer.cs

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

namespace _class
{
    class Customer
    {
        //Define four fields, data members
        public string name;
        public string address;
        public int age;
        public string buytime;

        //Define a method, function member
        public void Show()
        {
            Console.WriteLine("Customer Name:"+ name);
            Console.WriteLine("Customer address:"+ address);
            Console.WriteLine("Customer age:{0}", age);
            Console.WriteLine("Purchase time:{0}", buytime);
        }
        
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _class
{
    class Program
    {
        static void Main(string[] args)
        {
            //Because it can be used directly under the same project, if you don't need to introduce namespaces
            //1. Create and declare an object,
            Customer customer1;
            //2. Object initialization. It cannot be used without initialization. Use the new keyword for initialization
            customer1 = new Customer();
            customer1.name = "siki";
            Console.WriteLine(customer1.name);
            //Using methods in objects
            customer1.Show();
            //Console pause
            Console.ReadKey();
        }
    }
}

Operation results

2, Class declaration and use

Exercise 1:
Define a Vehicle class with run and stop methods and speed and maxspeed. weight field
Answer:
Create a new class file in the project and name it vehicle cs
Vehicle.cs

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

namespace _Class definition and declaration
{
    //Create a new vehicle class
    class Vehicle
    {
        public float speed;
        public float maxSpace;
        public float weight;

        //New method run

        public void Run()
        {
            Console.WriteLine("The vehicle is running at{0}m/s Speed forward", speed);
        }
		//New method stop
        public void Stop()
        {
            speed = 0;
            Console.WriteLine("Vehicle stop");
              
        }
    }
}

In program Call assignment in main of CS

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

namespace _005_Class definition and declaration
{
    class Program
    {
        static void Main(string[] args)
        {
            //Class. car1 is the instance
            Vehicle car1 = new Vehicle();
            //Assign vehicle speed to 100
            car1.speed = 100;
            //Call the run method of the Vehicle class
            car1.Run();
            //Call the stop method of the Vehicle class
            car1.Stop();
            Console.WriteLine("The current vehicle speed is:"+car1.speed);
            Console.ReadKey();
        }
    }
}

Operation results

Exercise 2:
Define a vector, ThreeVector, which contains three fields: x, y and z. there are methods to calculate the length and set the property
Use this variable to declare a variable (object)
Answer:
Create a new class of ThreeVector

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

namespace _Class definition and declaration
{
    class ThreeVector
    {
        //New x, y, z fields
        public float x;
        public float y;
        public float z;
        //New Length calculation method Length
        //Note that before the function, the type format is float, not void, and there is a return value
        public float Length()
        {
            //Calculate the length according to xyz and return
            return (float)Math.Sqrt(x * x + y * y + z * z);
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _Class definition and declaration
{
    class Program
    {
        static void Main(string[] args)
        {
            //Class. vector1 is the instance
            ThreeVector vector1 = new ThreeVector();
            //assignment
            vector1.x = 1;
            vector1.y = 1;
            vector1.z = 1;
            Console.WriteLine("The current vector length is:{0}", vector1.Length()) ;
            Console.ReadKey();
        }
    }
}

Operation results

In terms of programming specification, if the field in the class is set to private, the method can only be carried out inside the class and cannot be accessed. The above cannot be assigned in the main function

It is illegal to provide modification for the field. The code is as follows
ThreeVector.cs

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

namespace _Class definition and declaration
{
    class ThreeVector
    {
        //New x, y, z fields
        private float x;
        private float y;
        private float z;

        //Set the set method for the field to set the value of the field
        //If we directly access variables with the same name inside the method, we will give priority to the nearest formal parameter
        //Using this keyword, you can identify the variable as in the current class without ambiguity
        public void SetX(float x) 
        { 
            this.x = x;
        }
        public void SetY(float y)
        {
            this.y = y;
        }
        public void SetZ(float z)
        {
            this.z = z;
        }
        public float Length()
        {
            //Calculate the length according to xyz and return
            return (float)Math.Sqrt(x * x + y * y + z * z);
        }
    }
}

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

namespace _Class definition and declaration
{
    class Program
    {
        static void Main(string[] args)
        {
            //Class. vector1 is the instance
            ThreeVector vector1 = new ThreeVector();
            //assignment
            //vector1.x = 1;
            //vector1.y = 1;
            //vector1.z = 1;
            //Assignment by set method
            vector1.SetX(2);
            vector1.SetY(2);
            vector1.SetZ(2);
            Console.WriteLine("The current vector length is:{0}", vector1.Length()) ;
            Console.ReadKey();
        }
    }
}

Operation results

3, Constructor

When we construct an object, the initialization of the object is completed automatically, but we don't want to return to the default system value when we tie up the initialization object
A constructor is a function that initializes data
The syntax of declaring a basic constructor is to declare a method with the same name as the class, but no return type
For example, in the ThreeVector class above, you can add a public ThreeVector() function
ThreeVector.cs

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

namespace _Class definition and declaration
{
    class ThreeVector
    {
        //Build a constructor for initialization
        //Constructors can take parameters or no parameters
        public ThreeVector(float x, float y, float z) 
        {
            Console.WriteLine("The constructor was called,The original constructor is disabled");
            //Initialize x, y, z
            this.x = x;
            this.y = y;
            this.z = z;

        }

        public float Length()
        {
            //Calculate the length according to xyz and return
            return (float)Math.Sqrt(x * x + y * y + z * z);
        }
    }
}

Main.cs

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

namespace _005_Definition and class declaration
{
    class Program
    {
        static void Main(string[] args)
        {
            ThreeVector vector1 = new ThreeVector(3,3,3);
            Console.WriteLine("The current vector length is:{0}", vector1.Length()) ;
            Console.ReadKey();
        }
    }
}

4, Attributes

Properties and fields are different, including two modules: set and get
Access property is the same as access field. get will be called when getting data, and set will be called when setting data
ThreeVector.cs

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

namespace _005_Class definition and declaration
{
    class ThreeVector
    {
        //Create a new attribute
        public int MyintProperty 
        {
            //A get is required
            set 
            {
                //Used for assignment
                //
                Console.WriteLine("Property set Block called");
                Console.WriteLine("set of value Value of"+value);
            }
            //A set is required
            get
            {
                //Used to set the return value
                Console.WriteLine("Property get Block called");
                return 100;
            }
          //A set is required
        }
    }
}

Main.cs

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

namespace _Class definition and declaration
{
    class Program
    {
        static void Main(string[] args)
        {
            //Using attributes is the same as using fields
            //Instance initialization
            ThreeVector vector1 = new ThreeVector();
            //Assignment operation
            vector1.MyintProperty = 0;
            //Value operation
            int temp = vector1.MyintProperty;
            Console.WriteLine("temp: {0}", temp);
            Console.ReadKey();
        }
    }
}

5, Summary

The set and get of the property can exist at any time, but they do not have to exist at the same time
If there is no get, the value cannot be obtained, and if there is no set, the value cannot be assigned
1. Access fields through attributes
ThreeVector.cs

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

namespace _005_Class definition and declaration
{
    class ThreeVector
    {
        //New private x, y, z fields
        private float x;
        private float y;
        private float z;
        //Set properties to access fields through properties, which can also be called get and set methods
        public float X 
        {
            get { return x; }
            set { x = value; }
        }
    }
}

Main.cs

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

namespace _005_Class definition and declaration
{
    class Program
    {
        static void Main(string[] args)
        {
            ThreeVector vector1 = new ThreeVector();
            vector1.X = 100;
            Console.WriteLine("X: {0}", vector1.X);
            Console.ReadKey();

        }
    }
}


2. Short form of attribute

//The compiler will automatically provide me with a field to store, and the effect is the same as above
public float X { get; set; }

Keywords: C# linq

Added by Leshiy on Fri, 04 Feb 2022 16:39:59 +0200