Cpp to C #'s easy tutorial

It's very psychedelic. I've been working as an MCU in college and studying C/Cpp and python. I dreamed of becoming a back-end programmer one day, but I didn't hold much hope. Qiuzhao's job search is also the direction of MCU/Linux. I didn't expect to get a back-end offer in the end, but Linux still has to do it. It directly gave me an embedded full stack on the offer, and looked up to me 233. However, there is more to learn. Because the company is engaged in the industrial Internet of things, the main solution is to develop ASP.NET on win and then migrate to Linux environment. The whole embedded stack can not be relaxed. Study hard and improve your learning ability, so that you can achieve 100% with half the effort in the project. So I have to change my old style. I won't record some basic grammar and concepts. I will record some typical examples. Let's get familiar with others in the project application. bb end and start to record some core knowledge of c#.

Some different concepts:


C #: C # is designed for the common language infrastructure (CLI). The CLI consists of executable code and runtime environment, allowing the use of various high-level languages on different computer platforms and architectures.

C#/.NET CORE/.NET Framework/.NET Standard

  1. C #: programming language, which specifies the programming rules.
  2. . NET Core: a cross platform (Win Linux Mac) framework that allows c# to run on the platform it provides and provides it with rich class libraries. C # is an actor and. NET Core is the stage. Of course, this stage is not only c# a person's stage, VB and F# can also be used, but the most important thing is c#, which is the top card.
  3. . NET Framework: supports windows and Web applications. Today, you can build Windows applications in the. NET Framework using Windows Forms, WPF, and UWP
  4. . NET Standard: a set of rules or standards that specify which API s the. NET platform must implement. This will unify the. NET platform and prevent future fragmentation.
  5. XAMARIN: enables. NET to run on the mobile end. The company was later acquired by Microsoft

Know her before you enjoy the service

C# programmers can not care too much about the underlying implementation and boldly shine on the platform provided by. NET. But I mean, it's best to know a little about him:
Compared with unmanaged code such as C/Cpp, what is the process of c#'s managed code reaching the operating system?

The architecture of the. NET framework includes:

  • CLR is the Common Language Runtime [manage memory allocation, start or delete thread processes, implement security policies, and meet the requirements of current components for other components]
  • BCL is the Base Class Library
  • ADO.NET is a new data access framework, which meets three important requirements that ADO cannot meet: it provides a disconnected data access model, which is very important to the Web environment; It provides close integration with XML; It also provides seamless integration with. NET framework
  • Active service enterprise page (ASP.NET) provides a unified Web development model, including various services and new controls required for developers to generate enterprise Web applications. It is a compiled application based on. NET environment and can be created in any. NET compatible language.

Compilation and running of. NET program

Let's start with a few nouns:
Just in time JIT compiler
Common Intermediate Language CIL common intermediate language.

When. NET compiles the code, it will compile the high-level programming language into the intermediate language CIL and run it on the CLR, that is, integrate the code into an exe file,
. NET is not directly compiled into the code recognized by CPU in the compilation process, but into the code recognized by CLR, which lays a foundation for cross platform.
For example, the code we write in C language should be transplanted to C # as long as there is a corresponding compiler (JIT) in C # at this time, we can directly compile the CLR, that is, exe file compiled from another language.
Generally speaking, the compilation process is a language that users can understand, such as Console.WriteLine("hello,world"); Program into the code recognized by CLR, that is, the integrated exe file.
Then it is compiled by CLR into 0 and 1.0 recognized by CPU

Grammar, mainly different from C/CPP

variable

The variable definitions of C/CPP/C # are the same and direct. They are the nouns of the storage area operable by the program. Each variable has a specific type, which determines the size and layout of variable storage

data type

The data types of C # are mainly divided into the following parts:

  1. Value type
  2. reference type
  3. Pointer type

You can directly apply for a value type variable and store the value. Unlike C/CPP, value type variables are objects, and different value types are derived from System.ValueType
The reference type inherits from the System.Object class and the parent class of System.ValueType. System.ValueType itself is a class type, not a value type. The key is that ValueType overrides the Equals() method to compare value types according to the value of the instance rather than the reference address. Structure struct is directly derived from system. ValueType;

**Value types: * * various integer types (System.Int16), floating point type (System.Double), bool type (alias of System.Boolean), enumeration derived from System.Enum), nullable type (derived from System.Nullable generic structure, T? Is actually an alias of System.Nullable)
Each value type has an implicit default constructor to initialize the default value of that type. For example:

C # provides a special data type, nullable type (nullable type). Nullable type can represent the value within the normal range of its basic value type, plus a null value.
For example, nullable < Int32 >, read as "nullable Int32", can be assigned any value between - 2147483648 and 2147483647, or null. Similarly, the nullable < bool > variable can be assigned true or false or null.
The ability to assign null to numeric or Boolean types is particularly useful when dealing with databases and other data types that contain elements that may not be assigned. For example, a Boolean field in a database can store the value true or false, or the field can be undefined.
Format: < data_ type> ? < variable_ name> = null;

int i = new int();

Equivalent to:

Int32 i = new Int32();

Reference type: array (derived from System.Array), class derived from System.Object, delegate derived from System.Delegate), string (alias of System.String)

be careful:
Reference types can derive new types, but value types cannot;
The reference type can contain null value, and the value type cannot (the nullable type function allows null to be assigned to the value type);
The assignment of reference type variable only copies the reference to the object, not the object itself. When you assign a value type variable to another value type variable, the contained value is copied.

string s1 = "a";

string s2 = s1;

s1 = "b";//s2 is still "a"

Changing the value of s1 has no effect on s2. This makes string look more like a value type. In fact, this is the result of operator overloading. When s1 is changed,. NET reallocates memory for s1 on the managed heap. The purpose of this is to implement a string as a reference type as a string under normal semantics.
(Note: @ "xxxx" such as @ "C:\Windows" means to treat the escape character \ as a normal character)

The pointer type is the same as that on C/CPP.

Operators and branch statements are basically the same as C/CPP

C # has Null merge operator (?)
The Null merge operator is used to define default values for nullable and reference types. The Null merge operator defines a default value for type conversion to prevent nulls for nullable types. The Null merge operator implicitly converts the operand type to the type of an operand of another nullable (or non nullable) value type.
If the value of the first operand is null, the operator returns the value of the second operand; otherwise, it returns the value of the first operand. The following example demonstrates this:

 double? num1 = null;
               double? num2 = 3.14157;
               double num3;
               num3 = num1 ?? 5.34;      
               Console.WriteLine("num3 Value of: {0}", num3);
               num3 = num2 ?? 5.34;
               Console.WriteLine("num3 Value of: {0}", num3);
               Console.ReadLine();
============================================
	  num3 Value of: 5.34
      num3 Value of: 3.14157

Circular statement

A little different, mainly foreach, can iterate over an array or a collection object. python like syntax

foreach (var v in list)
{

}

array

1. The format of the declaration has changed

datatype[] arrayName;

datatype represents the type of array element
Dimension of array specified in []
arrayName is the identity of the array

To declare a multidimensional array:

 int [ , , ] m;

When accessing:

   /* An array with 5 rows and 2 columns */
int[,] a = new int[5, 2] {{0,0}, {1,2}, {2,4}, {3,6}, {4,8} };
int i, j;
/* Outputs the value of each element in the array */
for (i = 0; i < 5; i++)
{
	for (j = 0; j < 2; j++)
	{
		Console.WriteLine("a[{0},{1}] = {2}", i, j, a[i,j]);
	}
}

2. The concept has changed
C #'s array is a reference type. You must use new to create an array instance

structure

Structures can have methods, fields, indexes, properties, operators, methods, and events.
Structure can define a constructor, but cannot define a destructor. However, you cannot define a default constructor for a structure. The default constructor is automatically defined and cannot be changed.
Unlike classes, structures cannot inherit from other structures or classes.
Structure cannot be used as the infrastructure of other structures or classes.
Structure can implement one or more interfaces.
Structure members cannot be specified as abstract, virtual, or protected.
When you create a structure object using the New operator, the appropriate constructor is called to create the structure. Unlike classes, structures can be instantiated without using the New operator.
If the New operator is not used, the field is assigned and the object is used only after all fields are initialized.

Namespace

When using, you do not need to write a namespace, which is the same as when declaring

using System

Operator overloading

Defined by the symbol of the keyword operator followed by the operator

public static Box operator+ (Box b, Box c)
    {
       Box box = new Box();
       box.length = b.length + c.length;
       box.breadth = b.breadth + c.breadth;
       box.height = b.height + c.height;
       return box;
    }

Exception handling is basically the same

Exception classes in C # are mainly derived directly or indirectly from the System.Exception class.
The System.ApplicationException and System.SystemException classes are exception classes derived from the System.Exception class.
The System.ApplicationException class supports exceptions generated by applications. Therefore, programmer defined exceptions should be derived from this class.
The System.SystemException class is the base class for all predefined system exceptions.

Same pretreatment

File processing

A file is a collection of data stored on disk with a specified name and directory path. When a file is opened for reading and writing, it becomes a stream.

Basically, a stream is a sequence of bytes passed through a communication path. There are two main streams: input stream and output stream. The input stream is used to read data from a file (read operation), and the output stream is used to write data to a file (write operation).
C# I/O class
The System.IO namespace has various classes for performing various file operations, such as creating and deleting files, reading or writing files, closing files, etc.
Detailed inquiry manual

method

The method of C # is very similar to that of Cpp, and there are great differences in parameter transfer:
There are three ways to pass parameters to a method:

  • Value parameter
  • reference parameter
  • Output parameters

The value transfer parameter is the same as C/Cpp
The definition of reference passing parameters is as follows:
A reference parameter is a reference to the memory location of a variable. When parameters are passed by reference, unlike value parameters, it does not create a new storage location for these parameters. The reference parameter represents the same memory location as the actual parameter supplied to the method.
The reference passing mechanism is the same as that of Cpp
The form is slightly different: in C# the ref keyword is used to declare the reference parameter.

publicvoid swap(ref int x,ref int y)
{
		int temp;
		temp = x;/* Save the value of x */
		x = y;/* Assign y to x */
		y = temp;/* Assign temp to y */
}

Pass by output
The return statement can be used to return only one value from a function. However, you can use output parameters to return two values from a function. The output parameter assigns the data output by the method to itself, which is similar to the reference parameter in other aspects.
To put it bluntly, the out modifier is used to indicate that the incoming variable can get data from the function, rather than the life of the local variable in the function ends at the end of the function
Variables supplied to output parameters do not need to be assigned. Output parameters are particularly useful when you need to return a value from a method whose parameters do not specify an initial value.

Class access modifier

Class is basically the same as Cpp
Access modifier:

  1. Public: all objects are accessible
  2. Private: the object itself can be accessed inside the object
  3. Protected: only this class object and its subclass objects can be accessed (subclass objects inside other assemblies can also be accessed)
  4. Internal: objects in the same assembly can be accessed
  5. Protected Internal: derived classes within this assembly are accessible (subclass objects within other assemblies are not accessible)

inherit

Basically the same as Cpp inheritance
Inheritance is one of the most important concepts in object-oriented programming. Inheritance allows us to define one class according to another, which makes it easier to create and maintain applications. At the same time, it is also conducive to reusing code and saving development time.
The idea of inheritance realizes the belonging (IS-A) relationship. For example, mammals belong to (IS-A) animals, dogs belong to (IS-A) mammals, so dogs belong to (IS-A) animals.

The initialization of the base class is very important: the derived class inherits the member variables and member methods of the base class. Therefore, the parent object should be created before the child object is created. You can initialize the parent class in the member initialization list.
In inheritance, a subclass can explicitly call the constructor of the parent class in the constructor to initialize the members of the parent class.

public Tabletop(double l, double w) : base(l, w)

If there is no explicit call, the compiler will automatically call the default constructor of the parent class for you. Because the compiler is very stupid, it may face some problems in the process of automatic invocation.

1. The parent class does not declare a constructor, and the child class does not explicitly call the parent class constructor

If the parent class does not declare a constructor, the compiler will generate a default parameterless constructor for it. If a subclass does not explicitly call the parent class constructor, the compiler will call the default parameterless constructor of the parent class for him.

2. The parent class declares a parameter constructor, and the child class does not explicitly call the parent constructor

If the parent class declares a parameterless constructor, the compiler will not generate a parameterless constructor for it. If the child class does not explicitly call the parent constructor, and there is no parameterless constructor that can be called automatically, an error will be reported.

Another solution: the parent constructor uses default parameters

polymorphic

One interface, multiple functions
It can be divided into static polymorphism and dynamic polymorphism

Static: function overloading and operator overloading
Dynamic:
1. Use the abstract keyword to create an abstract class, which is used to provide the implementation of some classes of the interface. When a derived class inherits from the abstract class, the implementation is complete. Abstract classes contain abstract methods that can be implemented by derived classes. Derived classes have more professional functions.
2. Use the virtual keyword to create a virtual method, which can be implemented in inherited classes and different implementations in different inherited classes.

You cannot create an instance of an abstract class.

You cannot declare an abstract method outside an abstract class.

You can declare a class as a sealed class by placing the keyword sealed in front of the class definition. When a class is declared sealed, it cannot be inherited. Abstract classes cannot be declared as
sealed.

Interface

Interface defines the syntax contract that all classes should follow when inheriting the interface. The interface defines the "what" part of the syntax contract, and the derived class defines the "how" part of the syntax contract.

An interface defines properties, methods, and events, which are members of the interface. The interface contains only member declarations. The definition of a member is the responsibility of a derived class. Interface provides the standard structure that derived classes should follow.

Interfaces make the classes or structures that implement interfaces consistent in form.

Abstract classes are similar to interfaces to some extent, but most of them are only used when only a few methods are declared by the base class and implemented by the derived class.

Rules:
If an interface inherits from other interfaces, the implementation class or structure needs to implement the members of all interfaces.

    using System;
    interface IParentInterface
    {
        void ParentInterfaceMethod();
    }
    interface IMyInterface : IParentInterface
    {
        void MethodToImplement();
    }
    class InterfaceImplementer : IMyInterface
    {
        static void Main()
        {
            InterfaceImplementer iImp = new InterfaceImplementer();
            iImp.MethodToImplement();
            iImp.ParentInterfaceMethod();
        }
        public void MethodToImplement()
        {
            Console.WriteLine("MethodToImplement() called.");
        }
        public void ParentInterfaceMethod()
        {
            Console.WriteLine("ParentInterfaceMethod() called.");
        }
    }

effect;
(1) The same behavior of unrelated classes can be realized through the interface without knowing the class corresponding to the object.

(2) Through the interface, you can specify the methods that multiple classes need to implement.

(3) Through the interface, you can understand the interactive interface of the object without knowing the corresponding class of the object.

Of course, you can write methods directly in classes without interfaces, but if your group of methods need to be implemented in many classes, wouldn't it be better to abstract them into an interface specification?

attribute

The attribute of C # is a more powerful existence than the field. The field of an object can be accessed and assigned, and the attribute is the extension of the field. We can access it through the same syntax as the field. However, due to the syntax sugar, the accessor will be used internally for this access:

      using System;
      namespace tutorialspoint
      {
         class Student
         {
            private string code = "N.A";
            private string name = "not known";
            private int age = 0;
            // Declare a Code attribute of type string
            public string Code
            {
               get
               {
                  return code;
               }
               set
               {
                  code = value;
               }
            }
            // Declare the Name attribute of type string
            public string Name
            {
               get
               {
                  return name;
               }
               set
               {
                  name = value;
               }
            }
            // Declare an Age attribute of type int
            public int Age
            {
               get
               {
                  return age;
               }
               set
               {
                  age = value;
               }
            }
            public override string ToString()
            {
               return "Code = " + Code +", Name = " + Name + ", Age = " + Age;
            }
          }
          class ExampleDemo
          {
            public static void Main()
            {
               // Create a new Student object
               Student s = new Student();
               // Set the student's code, name, and age
               s.Code = "001";
               s.Name = "Zara";
               s.Age = 9;
               Console.WriteLine("Student Info: {0}", s);
               // Increase age
               s.Age += 1;
               Console.WriteLine("Student Info: {0}", s);
               Console.ReadKey();
             }
         }
      }
      =========================================
 result:
      Student Info: Code = 001, Name = Zara, Age = 9
      Student Info: Code = 001, Name = Zara, Age = 10

In fact, this writing method is to encapsulate data. Cpp, JAVA and python can also be implemented, but the implementation of C# is more elegant.

Abstract properties (vs abstract classes)

Abstract classes can have abstract properties that should be implemented in derived classes.
Note the following abstract that modifies the Name attribute and the virtual that modifies the implementation of the Name attribute

      using System;
      namespace tutorialspoint
      {
         public abstract class Person
         {
            public abstract string Name
            {
               get;
               set;
            }
            public abstract int Age
            {
               get;
               set;
            }
         }
         class Student : Person
         {
            private string code = "N.A";
            private string name = "N.A";
            private int age = 0;
            // Declare a Code attribute of type string
            public string Code
            {
               get
               {
                  return code;
               }
               set
               {
                  code = value;
               }
            }
            // Declare the Name attribute of type string
            public override string Name
            {
               get
               {
                  return name;
               }
               set
               {
                  name = value;
               }
            }
            // Declare an Age attribute of type int
            public override int Age
            {
               get
               {
                  return age;
               }
               set
               {
                  age = value;
               }
            }
            public override string ToString()
            {
               return "Code = " + Code +", Name = " + Name + ", Age = " + Age;
            }
         }
         class ExampleDemo
         {
            public static void Main()
            {
               // Create a new Student object
               Student s = new Student();
               // Set the student's code, name, and age
               s.Code = "001";
               s.Name = "Zara";
               s.Age = 9;
               Console.WriteLine("Student Info:- {0}", s);
               // Increase age
               s.Age += 1;
               Console.WriteLine("Student Info:- {0}", s);
               Console.ReadKey();
             }
         }
      }

Indexer

What is it?
Indexer allows an object to be indexed like an array. When you define an indexer for a class, the class behaves like a virtual array. You can use the array access operator ([]) to access instances of this class.

What can it do?
The declaration of the indexer's behavior is somewhat similar to that of a property. Like properties, you can use get and set accessors to define indexers. However, the property returns or sets a specific data member, and the indexer returns or sets a specific value of the object instance. In other words, it divides the instance data into smaller parts, indexes each part, and gets or sets each part.

How do you write it?
Defining a property includes providing a property name. The indexer is defined without a name, but with the this keyword, which points to an object instance. The following example demonstrates this concept:

      using System;
      namespace IndexerApplication
      {
         class IndexedNames
         {
            private string[] namelist = new string[size];
            static public int size = 10;
            public IndexedNames()
            {
               for (int i = 0; i < size; i++)
               namelist[i] = "N. A.";
            }
            public string this[int index]
            {
               get
               {
                  string tmp;
                  if( index >= 0 && index <= size-1 )
                  {
                     tmp = namelist[index];
                  }
                  else
                  {
                     tmp = "";
                  }
                  return ( tmp );
               }
               set
               {
                  if( index >= 0 && index <= size-1 )
                  {
                     namelist[index] = value;
                  }
               }
            }
            static void Main(string[] args)
            {
               IndexedNames names = new IndexedNames();
               names[0] = "Zara";
               names[1] = "Riz";
               names[2] = "Nuha";
               names[3] = "Asif";
               names[4] = "Davinder";
               names[5] = "Sunil";
               names[6] = "Rubic";
               for ( int i = 0; i < IndexedNames.size; i++ )
               {
                  Console.WriteLine(names[i]);
               }
               Console.ReadKey();
            }
         }
      }
==============================================
      Zara
      Riz
      Nuha
      Asif
      Davinder
      Sunil
      Rubic
      N. A.
      N. A.
      N. A.

It can be seen that the function of indexer is to provide a means to set internal array properties through object name [index]

Tags: C#

Posted on Sun, 21 Nov 2021 03:27:03 -0500 by smokenwhispers