C # profile

C# is a modern, general purpose, object-oriented programming language.

.NET includes the.NET platform and the.NET FrameWork. The platform is the foundation on which applications run, and the framework provides the ability to support applications running on that platform.

C# can develop applications based on the.net platform.

To sum up, it is clear that installing some software on a computer requires additional installation. Net, and correspondingly: Java is both a language and a platform.

The.net framework

The.NET framework can develop Window applications, Web applications, and Web services.

Applicable to C#, C++, Visual Basic, Jscript, COBOL, etc

Core components:

Common Language Runtime-CLR,.NET Framework Class Library, Metadata and Components, Windows Windows Forms

C# integrated development environment (IDE)

visual studio

File structure

  • .slN solution file, click to open the whole project
  • .csproj project file
  • Cs class files

Solution files include project files, and project files include class files (code files)

Program structure

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

namespace _1.begin
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World, c #"); Console.ReadKey(); }}}Copy the code

Introducing namespaces

using System;

The using keyword is used to include the System namespace in your program. A program typically has multiple using statements.

Declaring a namespace

namespace _1.begin { }

A namespace contains a list of classes.

A namespace is a container for storing code, with a using import and a namespace declaration.

Class declarations

class Program { }

Classes contain data and method declarations used by programs. Classes typically contain multiple methods. Methods define the behavior of a class.

In this case, the Program class has only one Main method.

Define the Main method

Defines the Main method, which is the entry point for all C# programs. The Main method says what the class will do when it executes.

statements

WriteLine is a method of the Console class defined in the System namespace. This statement displays the message “Hello World, C#” on the screen.

annotation

  • Single-line comment //
  • Multi-line comments /**/
  • Function description ///

Other precautions: case sensitive, start with Main, end with semicolon, file name can be different from class name

Basic grammar

For a simple example, see the comments for the base language.

// Introduce the namespace using System; / / namespace declaration namespace RectangleApplication {/ / statement class Rectangle {/ / member variable double length; double width; // Member function public voidAcceptdetails() {length = 4.5; Width = 3.5; } public doubleGetArea()
        {
            return length * width;
        }
        public void Display()
        {
            Console.WriteLine("Length: {0}", length);
            Console.WriteLine("Width: {0}", width);
            Console.WriteLine("Area: {0}", GetArea()); Rectangle r = new Rectangle(); Rectangle r = new Rectangle(); r.Acceptdetails(); r.Display(); Console.ReadLine(); }}}Copy the code

identifier

An identifier is used to identify a class, variable, function, or any other user-defined item.

It’s simply a name.

  • The identifier must start with a letter, underscore (_), or @, and can be followed by a series of letters, digits (0-9), underscores (_), and @.
  • The first character in an identifier cannot be a number.
  • Identifiers must not contain any embedded Spaces or symbols, such as? – +! # % ^ & * () [] {}. : “‘ / \
  • Identifiers cannot be C# keywords. Unless they have an @ prefix. For example, @if is a valid identifier, but if is not, because if is a keyword.
  • Identifiers must be case sensitive. Upper and lower case letters are considered different letters.
  • Cannot be the same as the C# library name.

The keyword

Look at the following keywords, have an impression.

The data type

Value types

A total of 13 value types are easy to remember as follows:

Unsigned bytes are prefixed with u and byte with s.

Byte Short int Long Correspond to 8, 16, 32, and 64-bit integers respectively

Float double Decimal corresponds to 32 64 128-bit floating point numbers respectively

Bool Indicates a Boolean value

Char is a 16-bit character

The sizeof () statement

The expression sizeof(type) yields the storage sizeof an object or type in bytes, such as sizeof(int) = 4

Reference types

Object type

The Object Type is the ultimate base class for all data types in C#’s Common Type system-cts. Object is an alias of the System.Object class.

object obj;
Copy the code

Dynamic type

You can store any type of value in a dynamic data type variable. Type checking for these variables occurs at run time.

Dynamic Variable name = variable value; dynamic d = 20;Copy the code

Difference between object types and dynamic types: Type checking for object type variables occurs at compile time, whereas type checking for dynamic type variables occurs at run time.

It is a String

The String type allows you to assign any String value to a variable.

The String type is an alias of the System.String class. It is derived from the Object type.

String values can be assigned in two forms: quotes and @ quotes.

String str = "runoob.com"; // @ (called"Verbatim string") treat the escape character (\) as a normal character string STR = @"C:\Windows"; Equivalent string STR ="C:\\Windows";
Copy the code

Add: the difference between String and String

String is a class in C#, String is a.net Framework class (not blue in C# IDE). C# String maps to.net Framework String. If you use String, the compiler will compile it into String, So if you just use String you can make the compiler work a little bit less. If C# is used, string is recommended

Pointer types

A pointer type variable stores the memory address of another type. Pointers in C# have the same functionality as Pointers in C or C++.

Data type * pointer name char* CPTR; int* iptr;Copy the code

The difference between value types and reference types

The value type is stored in stack memory, and the variable name corresponds to the stack address, which holds the value of the variable.

Reference types are stored in heap memory and stack memory, and variable names correspond to stack addresses, which hold heap addresses, and heap addresses hold variable values.

Speed: value type access speed is fast, reference type access speed is slow.

The ValueType is inherited from system. ValueType and the reference type is inherited from system. Object.

Stored data: The value type represents the actual data, and the reference type represents a pointer or reference to data stored in the memory heap.

Type conversion

A cast is a conversion of data from one type to another.

It can be converted from a value type to a value type or from a value type to a reference type.

Implicit type conversion

C#’s default safe conversion does not result in data loss.

int a = 12;
object b = a;
Copy the code

Explicit casting (cast)

A cast character is required, which may cause data loss.

Double a = 12.823; int b = (int) a; // b=12Copy the code

Here are the conversion methods, using variables. The method name ()

  1. ToBoolean Converts the type to a Boolean if possible.

  2. ToByte converts a type to a byte type.

  3. ToChar converts the type to a single Unicode character type if possible.

  4. ToDateTime converts a type (integer or string type) to a date-time structure.

  5. ToDecimal converts a floating point or integer type to a decimal type.

  6. ToDouble converts the type to a double floating-point type.

  7. ToInt16 converts the type to a 16-bit integer.

  8. ToInt32 converts the type to a 32-bit integer type.

  9. ToInt64 converts the type to a 64-bit integer type.

  10. ToSbyte converts a type to a signed byte type.

  11. ToSingle converts a type to a small floating point type.

  12. ToString converts a type to a string type.

  13. ToType converts a type to a specified type.

  14. ToUInt16 converts the type to a 16-bit unsigned integer type.

  15. ToUInt32 converts the type to a 32-bit unsigned integer type.

  16. ToUInt64 converts the type to a 64-bit unsigned integer type.

Packing and unpacking

When a value type is converted to an object type, it is called boxing;

When an object type is converted to a value type, it is called unboxing.

Boxing can be converted implicitly, and unboxing must display the conversion/use the Convert function

// Box object obj; obj = 100; Object obj = 12; int b = (int) a; int c = Convert.ToInt32(a);Copy the code

variable

A variable is the name of a storage area on which a program operates, and its data type determines the size and layout of the variable.

Data type classification:

More complex are enum, class, object…

Variable definition and assignment instance

// Data type variable name, variable name,... int i, j, k; Int I = 100; int d = 3, f = 5; // Receive the value from the user // Note that console.readline () returns the string int num; num = Convert.ToInt32(Console.ReadLine());Copy the code

A static variable

There is no concept of global variables in C#, all variables must be operated on by instances of the class, which improves security, but in some cases is inadequate.

Static <data_type> <variable_name> = value;Copy the code

constant

Primitive type constant

Constants can be any basic data type, such as integer constants, floating-point constants, character constants, or string constants, and enumerated constants.

Integer constants

Prefix indicates base: 0x or 0x indicates hexadecimal, 0 indicates octal, and no prefix indicates decimal.

Suffixes indicate unsigned: U and L indicate unsigned and long, respectively. Suffixes can be uppercase or lowercase, and multiple suffixes can be combined in any order.

Floating-point constant

3.14159 /* Legal */ 314159E-5L /* Legal */ 510E /* Illegal: Incomplete exponent */ 210F /* Illegal: No decimal or exponent */. E55 /* Illegal: Missing integer or decimal */Copy the code

Character constants

String constant

Enclosed in double quotation marks “” or enclosed in at sign “”

string a = "hello, world";                  // hello, world
string b = @"hello, world";               // hello, world
string c = "hello \t world";               // hello     world
string d = @"hello \t world";               // hello \t world
string e = "Joe said \"Hello\" to me";      // Joe said "Hello" to me
string f = @"Joe said ""Hello"" to me";   // Joe said "Hello" to me
string g = "\\\\server\\share\\file.txt";   // \\server\share\file.txt
string h = @"\\server\share\file.txt";      // \\server\share\file.txt
string i = "one\r\ntwo\r\nthree";
string j = @"one
two
three";
Copy the code

Define constants

Static constant const

Values are determined at compile time, must be initialized at declaration time and cannot be changed later, and can be defined in classes and methods.

const <data_type> <constant_name> = value; Const double a = 3.14;Copy the code

Dynamic constant readonly

Values are determined at run time, can only be initialized at declaration time or in a constructor, and can only be defined in a class.

class Program
{
    readonlyint a=1; // Initialize at declaration timereadonlyint b; // init in the constructorProgram()
    {
        b=2;
    }
    static void Main() {}}Copy the code

The operator

Arithmetic operator

Add +, subtract -, multiply *, divide /, take module %, add ++, subtract

Modulo: Divide and take the remainder

Self-addition/subtraction:

C = a++: assigns a to C and then increments a. C = ++ A: assigns a to C and then increments aCopy the code

Relational operator

Equal ==, unequal! =, greater than >, less than <, greater than or equal to >=, less than or equal to <=

The return value is Boolean

Logical operator

And &&, or | |, non!

An operator

With %, or |, non ~, exclusive or ^, left < <, moves to the right > > fill (zero)

Bitwise operation requires converting the decimal system to binary system, and then converting it to the decimal system

A = 60 0011 1100 B = 13 0000 1101 A&B = 0000 1100 A|B = 0011 1101 A^B = 0011 0001 ~A = 1100 0011 A<<2 = 1111 0000 A>>2 = 0000, 1111,Copy the code

The assignment operator

Other operators

priority

Conditional statements

Ternary expressions? :

The switch of grammar

switch(name){
    case 'A' :
       // ...
       break; 
    case 'B' :
       // ..
       break; Default: /* Optional */ /...break; 
}
Copy the code

Looping statements

The foreach grammar

int[] fibarray = new int[] { 0, 1, 1, 2, 3, 5, 8, 13 };
foreach (int element in fibarray)
{
    System.Console.WriteLine(element);
}
Copy the code

encapsulation

Definition of encapsulation: “To enclose one or more items in a physical or logical package”

Access modifier

  • Public: all objects can be accessed.
  • Private: The object can be accessed internally.
  • Protected: Only objects of this class and their subclasses are accessible
  • Internal: objects in the same assembly can be accessed;
  • Protected internal: Access is limited to the current assembly or to types derived from the containing class. (Parallel relationship)

For example, if man A is the parent of his son B, wife C, and illegitimate son D, if we add modifiers to A’s affairs:

A, B, D know (A and all his sons know, wife C doesn’t) private events, only A knows (private? On her mind? Protected internal events A, B, C, AND D are all aware of, but no one else is

using System; Namespace RectangleApplication {rectangleRectangle {Rectangle = rectangleRectangles; Rectangle = rectangleRectangles; Rectangle = rectangleRectangles; Rectangle = rectangleRectangles; Rectangle = rectangleRectangles; private double width; public voidAcceptdetails()
        {
            Console.WriteLine("Please enter length:");
            length = Convert.ToDouble(Console.ReadLine());
            Console.WriteLine("Please enter width:");
            width = Convert.ToDouble(Console.ReadLine());
        }
        public double GetArea()
        {
            return length * width;
        }
        public void Display()
        {
            Console.WriteLine(Length: {0}", length);
            Console.WriteLine("Width: {0}", width);
            Console.WriteLine("Area: {0}", GetArea()); } }//end class Rectangle class ExecuteRectangle { static void Main(string[] args) { Rectangle r = new Rectangle(); r.Acceptdetails(); r.Display(); Console.ReadLine(); }}} In the above example, the member variables length and width are declared private, so they cannot be accessed by Main(). The member functions AcceptDetails() and Display() can access these variables. Because the member functions AcceptDetails() and Display() are declared public, they can be accessed by Main() using an instance r of the Rectangle class.Copy the code

Default modifier

If no access modifier is specified, the default access modifier for a class member is used, which is private.

methods

Definition and Invocation

define

<Access Specifier> <Return Type> <Method Name>(Parameter List)
{
   Method Body
}
Copy the code
  • Access Specifier: Access modifier that determines the visibility of a variable or method to another class.
  • Return type: Return type. A method can Return a value. The return type is the data type of the value returned by the method. If the method does not return any value, the return type is void.
  • Method name: Indicates the Method name. It is a unique identifier and case sensitive. It cannot be the same as other identifiers declared in a class.
  • Parameter list: A list of parameters, enclosed in parentheses, used to pass and receive data for a method. The argument list refers to the type, order, and number of arguments to a method. Parameters are optional, that is, a method may have no parameters.
  • Method body: The body of a Method that contains the set of instructions needed to complete a task.

call

Class instance, by instance. Method name () to call the method.

In the same namespace, methods can be called in the same class, or methods of another class can be called in one class.

Recursive calls

using System; Namespace CalculatorApplication {class NumberManipulator {public int factorial(int num) {/* Local variable definition */ int result;if (num == 1)
            {
                return 1;
            }
            else
            {
                result = factorial(num - 1) * num;
                returnresult; } } static void Main(string[] args) { NumberManipulator n = new NumberManipulator(); // Call the factorial method console. WriteLine("The factorial of 6 is {0}", n.factorial(6));
            Console.WriteLine(The factorial of 7 is {0}., n.factorial(7));
            Console.WriteLine("The factorial of 8 is {0}", n.factorial(8)); Console.ReadLine(); }}}Copy the code

Parameter passing

Pass parameters by value

The default way in which arguments are passed, the value of the actual argument is copied to the parameter, which uses two different in-memory values. Therefore, when the parameter value changes, it does not affect the value of the argument, thus ensuring the security of the real parameter data.

By value pass, we don’t mean data types. Even reference types can be passed by value.

using System; namespace CalculatorApplication { class NumberManipulator { public void swap(int x, int y) { int temp; temp = x; /* save x */ x = y; /* assign y to x */ y = temp; } static void Main(string[] args) {n = new args (); /* local variable definition */ int a = 100; int b = 200; Console.WriteLine("Before switching, the value of a: {0}", a);
         Console.WriteLine("Before switching, the value of b: {0}", b); /* call a function to swap values */ n.swp (a, b); Console.WriteLine("After the swap, the value of A: {0}", a);
         Console.WriteLine("After the swap, the value of b: {0}", b); Console.ReadLine(); }}} Output before the swap, a value: 100 before the swap, b value: 200 after the swap, A value: 100 after the swap, b value: 200Copy the code

Pass parameters by reference

The ref keyword is used to declare reference parameters, which pass the variable address to the method and interact with each other.

using System; namespace CalculatorApplication { class NumberManipulator { public void swap(ref int x, ref int y) { int temp; temp = x; /* save x */ x = y; /* assign y to x */ y = temp; } static void Main(string[] args) {n = new args (); /* local variable definition */ int a = 100; int b = 200; Console.WriteLine("Before switching, the value of a: {0}", a);
         Console.WriteLine("Before switching, the value of b: {0}", b); /* call function to swap values */ n.swp (ref a, ref b); Console.WriteLine("After the swap, the value of A: {0}", a);
         Console.WriteLine("After the swap, the value of b: {0}", b); Console.ReadLine(); }}} Output before swap, value of a: 100 before swap, value of b: 200 after swap, value of a: 200 after swap, value of b: 100Copy the code

Pass parameters as output

Use the out keyword to declare reference parameters, and output parameters assign themselves the data output by the method.

Variables supplied to output parameters do not require assignment. Output parameters are especially useful when you need to return a value from a method whose parameters do not specify an initial value.

using System; namespace CalculatorApplication { class NumberManipulator { public void getValue(out int x ) { int temp = 5; x = temp; } static void Main(string[] args) { NumberManipulator n = new NumberManipulator(); /* local variable definition */ int a = 100; Console.WriteLine("Before method call, the value of a: {0}", a); /* call the function to get the value */ n.gote value (out a); Console.WriteLine("After method call, the value of a: {0}", a); Console.ReadLine(); }}} output before the method call, a value: 100 after the method call, a value: 5Copy the code

The difference between ref and out

  • Whether initialization is required. The ref type must be initialized before a variable can be passed, or the compiler will report an error, whereas the out type does not need to be initialized

  • Ref passes variables and values into methods, while out does not pass data into methods. In other words, the ref type goes in and out, and the out type only goes out.

  • Out data must be assigned in a method, otherwise the compiler will report an error. So out has to come out, ref doesn’t.

  • The difference when you reload. When a method is overloaded, the compiler will report an error if the difference between the two methods is limited to the type ref in one argument and out in the other.

Control of parameter passing for complex reference types

Complex is when the parameters are array or collection types or contain data of those types, in which case the above method does not guarantee that the parameter data will not be modified, because the array or collection fields (properties) in the object can be modified even if the object is read-only.

1. Collection parameters (same for reference parameters containing collection fields)

Prior to.NET 4.5, it was possible to replace concrete collection types with interfaces that did not contain methods to modify collection elements. For example, use the IEnumerable interface instead of a List. Version 4.5 can directly use the IReadOnlyCollection interface or implement the collection type of the interface.

2. Array parameters

There is no good way to protect array type arguments from being modified, so avoid using array types as method arguments unless you are using optional arguments.

Nullable types

Nullable type?

A nullable type can represent a value within the normal range of its underlying value type, plus a null value.

Usage: The variable definition remains the same as before, except that the datatype is followed by? , such as int? num = 45; , so num can be assigned either a 32-bit integer or null.

Benefits: 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.

int i; // Default value 0 int? ii; // Default value nullCopy the code
using System; namespace CalculatorApplication { class NullablesAtShow { static void Main(string[] args) { int? num1 = null; int? num2 = 45; double? num3 = new double? (a); double? Num4 = 3.14157; bool? boolval = new bool? (a); // Display value console. WriteLine("Display nullable type values: {0}, {1}, {2}, {3}",
                            num1, num2, num3, num4);
         Console.WriteLine("A nullable Boolean: {0}", boolval); Console.ReadLine(); }}} Output shows the value of the nullable type:, 45,, 3.14157 A nullable Boolean value:Copy the code

Null merge operator??

The Null merge operator is used to define default values for nullable and reference types.

?? The operator returns the value of the second operand if the first operand is null, otherwise the first operand.

using System;
namespace CalculatorApplication
{
   class NullablesAtShow
   {
         
      static void Main(string[] args)
      {
         
         double? num1 = null;
         double? num2 = 3.14157;
         double num3;
         num3 = num1 ?? 5.34;      // num1 如果为空值则返回 5.34
         Console.WriteLine("Num3 value: {0}", num3);
         num3 = num2 ?? 5.34;
         Console.WriteLine("Num3 value: {0}", num3); Console.ReadLine(); }} The value of num3 is 5.34. The value of num3 is 3.14157Copy the code

The same effect can be achieved with ternary expressions

Array

A one-dimensional array

define

An array is a fixed – sized sequential collection of elements of the same type. All arrays consist of contiguous memory locations. An array is a reference type that requires the new keyword to create an instance of the array.

The statement

// datatype dimension arrayName datatype[] arrayName;Copy the code

Initialize the

Double [] balance = new double[10]; The balance [0] = 4500.0; Double [] balance = {2340.0, 4523.69, 3421.0}; double[] balance = {2340.0, 4523.69, 3421.0}; Int [] marks = new int[5] {99, 98, 92, 97, 95}; int[] marks = new int[5] {99, 98, 92, 97, 95}; Int [] marks = new int[] {99, 98, 92, 97, 95}; int[] score = marks;Copy the code

The default value

The C# compiler implicitly initializes each array element to a default value based on the array type. For example, all elements of an int array are initialized to 0.

The foreach traversal

using System; namespace ArrayApplication { class MyArray { static void Main(string[] args) { int [] n = new int[10]; /* n is an array of 10 integers */ /* initializes the elements in array n */for( int i = 0; i < 10; i++ ) { n[i] = i + 100; } /* Print the value of each array element */ foreach (int j)in n )
         {
            int i = j-100;
            Console.WriteLine("Element[{0}] = {1}", i, j); } Console.ReadKey(); Element[1] = 101 Element[2] = 102 Element[3] = 103 Element[4] = 104 Element[5] = 105 Element[6] = 106 Element[7] = 107 Element[8] = 108 Element[9] = 109Copy the code

Multidimensional array

The statement

// 2d string [,] names; Int [,,] m;Copy the code

Initialize the

/ / 2 d int [and] a = new int [3, 4] {{0, 1, 2, 3}, / * initializes the index number of 0 * / {4, 5, 6, 7}, / * initializes the index number of 1 * / {8, 9, 10, 11} /* Initializes line 2 */};Copy the code
/ / 3 d int [and] muarr = new int [2, 2, 3] {{{1, 2, 3}, {4 and 6}}, {{7,8,9}, {2 and 4}}};Copy the code

The values

An array is equivalent to a matrix

Int val = a[2,3];Copy the code

Iterate over a multidimensional array

Int [and] muarr = new int [2, 2, 3] {{{1, 2, 3}, {4 and 6}}, {{7,8,9}, {2 and 4}}}; int rank = muarr.Rank; Console.WriteLine("The dimension of this multidimensional array is :{0}",rank);
int rlength = muarr.GetLength(1);
Console.WriteLine("The second dimension of this multidimensional array has {0} elements.",rlength);
Console.WriteLine("Start traversing the multidimensional array");
Console.WriteLine("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -");
int wei = 0;
for(int i = 0; i < muarr.GetLength(0); i++ ) {for (int js1 = 0; js1< muarr.GetLength(1); js1++)
    {
        for(int js2 = 0; js2<muarr.GetLength(2); js2++) { Console.WriteLine("The lowest dimension {0} has a value of {1}",wei,muarr[i,js1,js2]); } ++wei; }}Copy the code

Jagged arrays

It’s essentially a one-dimensional array, an array of arrays

Different from multi-dimensional arrays: the length of each row in a jagged array can be different, while the length of each row in a multi-dimensional array is the same

The statement

int [][] scores;
Copy the code

Initialize the

Int [] [] scores = new int [2] [] {new int [],93,94 {92}, new int [],66,87,88 {85}};Copy the code

The values

scores[0][2]
Copy the code

The instance

Of course, this is an ideal example, because the length of each jagged array is different

using System; Namespace ArrayApplication {class MyArray {static void Main(string[] args) {/* An array of 5 integers */ int[][] a = new Int [] [] {new int [] {0, 0}, new int []} {1, 2, new int [] {2, 4}, new int [] {3, 6}, new int [] {4, 8}}; int i, j; /* Prints 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]); } } Console.ReadKey(); }}} to output a [0] [0] = 0 a [0] [1] = 0 a [1] [0] = 1 a [1] [1] = 2 a [2] [0] = 2 a [2] [3] [1] = 4 a [0] = 3 a [3] [1] = 6 a [4] [0] = 4 a[4][1] = 8Copy the code

Array as function arguments

A one-dimensional array

using System;

namespace ArrayApplication
{
   class MyArray
   {
      double getAverage(int[] arr, int size)
      {
         int i;
         double avg;
         int sum = 0;

         for (i = 0; i < size; ++i)
         {
            sum += arr[i];
         }

         avg = (double)sum / size;
         returnavg; } static void Main(string[] args) { MyArray app = new MyArray(); /* an int array with 5 elements */ int[] balance = new int[]{1000, 2, 3, 17, 50}; double avg; /* Pass pointer to array as parameter */ avg = app.getaverage (balance, 5); /* Output return value */ console. WriteLine("The average is: {0}", avg ); Console.ReadKey(); }}}Copy the code

Jagged arrays

using System; namespace ArrayApplication { class Program { static void Main(String[] args) { int[][] array = new int[3][]; array[0] = new int[] { 0, 1 }; array[1] = new int[] { 2, 3, 4 }; array[2] = new int[] { 5, 6, 7, 8 }; Program pro = new Program(); int summ=pro.getArea(array); // Function name as argument console. WriteLine("{0}", summ);
        }

        public int  getArea(int[][] array)
        {
            int sum=0;
            for(int j = 0; j < array.Length; j++ ) foreach (int iin array[j])
                    sum += i;
            returnsum; }}}Copy the code

Params parameter array

Parameter arrays are often used to pass an unknown number of arguments to a function.

Public return type method name (params type name [] array name)Copy the code
using System;

namespace ArrayApplication
{
   class ParamArray
   {
      public int AddElements(params int[] arr)
      {
         int sum = 0;
         foreach (int i in arr)
         {
            sum += i;
         }
         return sum;
      }
   }
     
   class TestClass
   {
      static void Main(string[] args)
      {
         ParamArray app = new ParamArray();
         int sum = app.AddElements(512, 720, 250, 567, 889);
         Console.WriteLine("The sum is {0}", sum); Console.ReadKey(); }}}Copy the code

Note:

  1. The parameter type with the params keyword must be a one-dimensional array and cannot be used on a multidimensional array.
  2. Ref and out cannot be used at the same time.
  3. The parameter with the params keyword must be the last parameter, and only one params keyword is allowed in the method declaration.
  4. You cannot use overloaded methods using params alone.
  5. Methods without the params keyword take precedence over methods with the params keyword

Array class

The Array class is the base class for all arrays in C# and is defined in the System namespace. The Array class provides a variety of properties and methods for arrays.

attribute

methods

Array. method name ()

String (String)

The string keyword is an alias of the System. string class used to declare string variables. Reference type.

Creating a String

  • By specifying a String to the String variable
  • By using the String class constructor
  • By using the string concatenation operator (+)
  • By retrieving a property or calling a method that returns a string
  • To convert a value or object to its string representation by formatting methods
using System; Namespace StringApplication {class Program {static void Main(string[] args) {// String constants""
            string fname, lname;
            fname = "Rowan";
            lname = "Atkinson"; // string connection + string fullName = fname + lname; Console.WriteLine("Full Name: {0}", fullname);

            //通过使用 string 构造函数
            char[] letters = { 'H'.'e'.'l'.'l'.'o' };
            string greetings = new string(letters);
            Console.WriteLine("Greetings: {0}", greetings); // The method returns the string string[] sarray = {"Hello"."From"."Tutorials"."Point" };
            string message = String.Join("", sarray);
            Console.WriteLine("Message: {0}", message); DateTime waiting = new DateTime(2012, 10, 10, 17, 58, 1); string chat = String.Format("Message sent at {0:t} on {0:D}",
            waiting);
            Console.WriteLine("Message: {0}", chat); Console.ReadKey() ; }}} Full Name: RowanAtkinson Greetings: Hello Message: Hello From Tutorials on Point Message: Message sent at 17:58 on Wednesday, 10 October 2012Copy the code

Property of the String class

String class method

1. Compare string string.pare (str1, str2) == 0 2. Contains the string str.Contains("test") 3. Intercept the Substring str.substring (23) 4. Join String String.join ("\n"// Starray is an array of stringsCopy the code

Structure (Struct)

The struct keyword is used to create structures, which are value type data structures.

define

Properties and methods can be defined internally, but initial values cannot be assigned

struct Books
{
   public string title;
   public string author;
   public string subject;
   public int book_id;
};  
Copy the code

The statement

// method 1 Books Book1; // Method 2: new Books Book1 = new Books();Copy the code

Initialize the

  1. After declaring the structure, passAttribute name = attribute valueTo initialize the
  2. An initialization function is defined inside the structure that receives parameters, assigns values to attributes, and is called by the declared instance to complete the initialization

The characteristics of

  • Structures can have methods, fields, indexes, attributes, operator methods, and events.
  • A structure can define a constructor, but not a destructor. However, you cannot define a no-argument constructor for a structure. The no-argument constructor (the default) is automatically defined and cannot be changed.
  • Unlike classes, structures cannot inherit from other structures or classes.
  • Structures cannot be used as infrastructure for other structures or classes.
  • A 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, fields are assigned and objects are not used until all fields have been initialized.

Comparison of classes and structures

  • Classes are reference types and structures are value types.
  • Classes can inherit; structures do not support inheritance.
  • Structures cannot declare default constructors.
  • Fields declared in a structure cannot be assigned initial values; classes can.

Structure can be more efficient and less costly when describing a lightweight object.

Because the objects of a class are stored in heap space, the structure is stored in the stack. The heap space is large, but the access speed is slow, and the stack space is small, and the access speed is relatively fast.

Enumeration (Enum)

Enumerations are a set of named integer constants. Enumeration types are value types declared using the enum keyword.

define

enum <enum_name>
{ 
    enumeration list 
};
Copy the code

use

(int)enum_name.list

using System;

public class EnumTest
{
    enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat };

    static void Main()
    {
        int x = (int)Day.Sun;
        int y = (int)Day.Fri;
        Console.WriteLine("Sun = {0}", x);
        Console.WriteLine("Fri = {0}", y); }}Copy the code

Each symbol in an enumerated list represents an integer value, an integer value greater than the symbol that precedes it. By default, the first enumeration symbol has a value of 0.

However, it is also possible to customize the value of each symbol:

using System; class Program { enum Day {a=8,b,c=1,e,f,g}; static void Main(string[] args) { int a = (int)Day.a; int e = (int)Day.e; Console.WriteLine(a); Console.WriteLine(e); Console.ReadKey(); }} output 8 2Copy the code

Class (Class)

An object is an instance of a class.

The definition of a class

Accessmodifier class class name {// Define attribute accessmodifier data type attribute name = attribute value; // Define method access modifier return type method name (parameter) {//... }}Copy the code

Supplement:

  • The default access modifier, class internal, member private
  • Pass point (.) The operator accesses a member of a class

Example:

using System; namespace BoxApplication { class Box { public double length; // public double lines; // width public double height; } class Boxtester {static void Main(string[] args) {Box Box1 = new Box(); // declare Box1 with type Box Box Box2 = new Box(); // declare Box2 with type Box double volume = 0.0; // size // Box1. Height = 5.0; Box1. Length = 6.0; Box1. Breadth = 7.0; // Box2. Height = 10.0; Box2. Length = 12.0; Box2. Breadth = 13.0; Width * width * breadth; Console.WriteLine("Box1 volume: {0}", volume); Width * width * breadth; Console.WriteLine("Box2 volume: {0}", volume); Console.ReadKey(); }}}Copy the code

encapsulation

Implement encapsulation: set member variables as private attributes, set specific member methods as common attributes, through these common methods to modify private attributes, so as to achieve encapsulation.

The constructor

The constructor of a class is a special member function of the class that is executed when a new object of the class is created.

The constructor name is exactly the same as the name of the class, and it does not have any return type.

using System; namespace LineApplication { class Line { private double length; // Line length publicLine()
      {
         Console.WriteLine("Object created"); } static void Main(string[] args) { Line line = new Line(); }}}Copy the code

Parameterized constructors

The default constructor does not take any arguments. But if you need a constructor that takes parameters you can take parameters, and that constructor is called a parameterized constructor.

using System; namespace LineApplication { class Line { private double length; Public Line(double len) public Line(double len) {console. WriteLine("Object created, length = {0}", len); length = len; } static void Main(string[] args) {Line Line = new Line(10.0); }}}Copy the code

Implicit constructors

If the instance constructor is not explicitly provided in the class declaration, in this case the compiler provides an implicit default constructor with the following characteristics:

(1) No parameters;

② The method body is empty.

If a constructor is declared, the declared constructor is used.

An error is reported if the declared constructor contains parameters that were not passed at instantiation time.

The destructor

The destructor of a class is a special member function of the class that is executed when the object of the class is out of scope.

The destructor name prefixes the name of the class with a wavy (~), and it returns no value and takes no arguments.

Destructors are used to free resources before terminating the program, such as closing files, freeing memory, and so on. Destructors cannot be inherited or overloaded.

using System; namespace LineApplication { class Line { private double length; // The length of the Line ~Line() // destructor {console.writeline ()"Object deleted"); } static void Main(string[] args) { Line line = new Line(); }}}Copy the code

Static members

When we declare a class member to be static, it means that no matter how many class objects are created, there will be only one copy of that static member. Static variables are used to define constants because their values can be obtained by calling the class directly without creating an instance of the class, since the static members already exist before the object is created.

using System; namespace ConsoleApp { class Program { static void Main(string[] args) { int num = AddClass.Add(2, 3); Console.WriteLine(num); } } class AddClass { public static int Add(int x,int y) {returnx + y; }}}Copy the code

Static variable instance:

using System;
namespace StaticVarApplication
{
    class StaticVar
    {
       public static int num;
        public void count()
        {
            num++;
        }
        public int getNum()
        {
            return num;
        }
    }
    class StaticTester
    {
        static void Main(string[] args)
        {
            StaticVar s1 = new StaticVar();
            StaticVar s2 = new StaticVar();
            s1.count();
            s1.count();
            s1.count();
            s2.count();
            s2.count();
            s2.count();        
            Console.WriteLine(Num: {0}, s1.getNum());
            Console.WriteLine(Num: {0}, s2.getNum()); Console.ReadKey(); Num: 6 s2: num: 6Copy the code

Static function examples:

Static functions can only access static variables. Static functions exist before the object is created.

using System;
namespace StaticVarApplication
{
    class StaticVar
    {
       public static int num;
        public void count()
        {
            num++;
        }
        public static int getNum()
        {
            return num;
        }
    }
    class StaticTester
    {
        static void Main(string[] args)
        {
            StaticVar s = new StaticVar();
            s.count();
            s.count();
            s.count();                  
            Console.WriteLine(Num: {0}, StaticVar.getNum()); Console.ReadKey(); Output variable num: 3Copy the code

inheritance

The existing class is called the base class, and the new class is called a derived class.

Class < derived > : < base > {... }Copy the code
  • Syntax for inheritance:{// Subclass body}
  • Inheritance features: A subclass owns all the fields, attributes, and methods of its parent class
  • A class can have multiple subclasses, but only one parent class.
  • A class that inherits from another class can also be inherited from other classes
  • In C#, all classes inherit directly or indirectly from the Object class

Base class access (access to hidden base class members)

A base class access expression consists of the keyword base followed by a dot and the name of the member. Such as:

Console.WriteLine("{0}",base.Field1);
Copy the code

Initialization of the base class

using System; Namespace RectangleApplication {rectangleRectangle {rectanglerectangle {Rectangle = rectangleRectangle; protected double width; public Rectangle(double l, double w) { length = l; width = w; } public doubleGetArea()
      {
         return length * width;
      }
      public void Display()
      {
         Console.WriteLine(Length: {0}", length);
         Console.WriteLine("Width: {0}", width);
         Console.WriteLine("Area: {0}", GetArea());
      }
   }//end class Rectangle  
   class Tabletop : Rectangle
   {
      private double cost;
      public Tabletop(double l, double w) : base(l, w)
      { }
      public double GetCost()
      {
         double cost;
         cost = GetArea() * 70;
         return cost;
      }
      public void Display()
      {
         base.Display();
         Console.WriteLine("Cost: {0}", GetCost()); }} class ExecuteRectangle {static void Main(string[] args) {Tabletop t = new Tabletop(4.5, 7.5); t.Display(); Console.ReadLine(); }} output length: 4.5 Width: 7.5 Area: 33.75 Cost: 2362.5Copy the code

Use interfaces to implement multiple inheritance

using System;
namespace InheritanceApplication
{
   class Shape
   {
      public void setWidth(int w)
      {
         width = w;
      }
      public void setHeight(int h) { height = h; } protected int width; protected int height; } // PaintCost public interface PaintCost {int getCost(int area); } class Rectangle: Shape, PaintCost {public intgetArea()
      {
         return (width * height);
      }
      public int getCost(int area)
      {
         returnarea * 70; } } class RectangleTester { static void Main(string[] args) { Rectangle Rect = new Rectangle(); int area; Rect.setWidth(5); Rect.setHeight(7); area = Rect.getArea(); // Print the area of the object console. WriteLine("Total area: {0}",  Rect.getArea());
         Console.WriteLine("Total cost of paint:The ${0}", Rect.getCost(area)); Console.ReadKey(); Total output area: 35 Total paint cost:The $2450
Copy the code

An object can be declared with a parent class, but instantiated with a subclass

This instance is subclassed, but because you declare it with the parent class, you cannot access the subclass’s own members in the normal way, only the members inherited from the parent class.

When a subclass overrides a virtual method declared by virtual in its parent class with Override, the parent class instantiates the method and the method overridden in the subclass is invoked.

If a subclass overrides a virtual method declared by virtual from its parent class with new, it instantiates the parent class and calls the virtual method in the parent class.

polymorphism

Polymorphism is the ability to have many different manifestations or forms of the same behavior, which is simply “one interface, many functions”.

Static polymorphism and dynamic polymorphism

In static polymorphism, the response of a function occurs at compile time. In dynamic polymorphism, the response of a function occurs at run time.

Static polymorphism

  • Function overloading
  • Operator overloading

Function overloading

The function name is the same, but the function definition is different (for example, the number of parameters, the parameter type is different), but the return type can not be different.

Operator overloading

Built-in operators in C# can be redefined or overridden by the keyword operator followed by the operator’s symbol

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;
}
Copy the code

The above function implements the addition operator (+) for the user-defined class Box.

It adds the properties of the two Box objects and returns the added Box object.

Dynamic polymorphism

Dynamic polymorphism is implemented through abstract classes and virtual methods.

An abstract class

Use the keyword abstract to create an abstract class that provides a partial class implementation of the interface. Implementation is complete when a derived class inherits from the abstract class. Abstract classes contain abstract methods that can be implemented by derived classes. Derived classes have more specialized functionality.

Example:

using System;
namespace PolymorphismApplication
{
   abstract class Shape
   {
       abstract public int area();
   }
   class Rectangle:  Shape
   {
      private int length;
      private int width;
      public Rectangle( int a=0, int b=0)
      {
         length = a;
         width = b;
      }
      public override int area ()
      {
         Console.WriteLine("Rectangle class size:");
         return (width * length);
      }
   }

   class RectangleTester
   {
      static void Main(string[] args)
      {
         Rectangle r = new Rectangle(10, 7);
         double a = r.area();
         Console.WriteLine("Area: {0}",a); Console.ReadKey(); }}} Rectangle class size: 70Copy the code

Virtual method

Virtual methods are declared using the keyword virtual and can have different implementations in different inherited classes, and calls to virtual methods occur at run time.

Virtual and abstract

  1. The virtual modifier must have an implementation (even if it’s just adding braces), while the abstract modifier must not.
  2. Virtual can be overridden by subclasses, whereas abstract must be overridden by subclasses.
  3. If a class member is decorated with abstract, the class must be preceded by abstract because only abstract classes can have abstract methods.
  4. Cannot create an instance of an abstract class, can only be inherited and cannot be instantiated.

Dynamic polymorphism

using System;
namespace PolymorphismApplication
{
   class Shape
   {
      protected int width, height;
      public Shape( int a=0, int b=0)
      {
         width = a;
         height = b;
      }
      public virtual int area()
      {
         Console.WriteLine("Area of parent class:");
         return 0;
      }
   }
   class Rectangle: Shape
   {
      public Rectangle( int a=0, int b=0): base(a, b)
      {

      }
      public override int area ()
      {
         Console.WriteLine("Rectangle class size:");
         return (width * height);
      }
   }
   class Triangle: Shape
   {
      public Triangle(int a = 0, int b = 0): base(a, b)
      {
     
      }
      public override int area()
      {
         Console.WriteLine("Triangle class area:");
         return (width * height / 2);
      }
   }
   class Caller
   {
      public void CallArea(Shape sh)
      {
         int a;
         a = sh.area();
         Console.WriteLine("Area: {0}", a); } } class Tester { static void Main(string[] args) { Caller c = new Caller(); Rectangle r = new Rectangle(10, 7); Triangle t = new Triangle(10, 5); c.CallArea(r); c.CallArea(t); Console.ReadKey(); Rectangle = = = = = = = = = = = = = = = = = = = = = = =Copy the code

interface

Interfaces contain only declarations of members, whose definition is the responsibility of derived classes, and provide a standard structure that derived classes should follow.

The statement

Interfaces are declared using the interface keyword, which is similar to class declarations. Interface declarations are public by default.

using System; Interface IMyInterface {// Interface member void implement (); } class InterfaceImplementer : IMyInterface { static voidMain()
    {
        InterfaceImplementer iImp = new InterfaceImplementer();
        iImp.MethodToImplement();
    }

    public void MethodToImplement()
    {
        Console.WriteLine("MethodToImplement() called."); }}Copy the code

Generally, interface commands start with the letter I

Interface inheritance

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."); }}Copy the code

The namespace

Namespaces are designed to provide a way to separate a set of names from others.

The name of a class declared in one namespace does not conflict with the name of the same class declared in another namespace.

Simply put: equivalent to different folders under the same file name.

Declaration and use of namespaces

using System;
namespace first_space
{
   class namespace_cl
   {
      public void func()
      {
         Console.WriteLine("Inside first_space");
      }
   }
}
namespace second_space
{
   class namespace_cl
   {
      public void func()
      {
         Console.WriteLine("Inside second_space");
      }
   }
}  
class TestClass
{
   static void Main(string[] args)
   {
      first_space.namespace_cl fc= new first_space.namespace_cl(); second_space.namespace_cl sc = new second_space.namespace_cl(); fc.func(); sc.func(); Console.ReadKey(); }} Inside first_space Inside second_spaceCopy the code

Using keywords

  1. Introduce namespaces so that they are not preceded by namespace names when used
using System;
using Namespace1.SubNameSpace;
Copy the code
  1. Using static directive: Specifies a type whose static members can be accessed without specifying a type name
using static System.Math; var = PI; // Use system.math.pi directlyCopy the code
  1. names
using Project = PC.MyCompany.Project;
Copy the code
  1. Using statement: Binds instances to code
using (Font font3 = new Font("Arial", 10.0f),
            font4 = new Font("Arial", 10.0f)) {// Use font3 and font4.}Copy the code

Nested namespaces

Point of use (.) Operator to access a member of a nested namespace

using System;
using SomeNameSpace;
using SomeNameSpace.Nested;

namespace SomeNameSpace
{
    public class MyClass
    {
        static void Main()
        {
            Console.WriteLine("In SomeNameSpace"); Nested.NestedNameSpaceClass.SayHello(); }} // Namespace Nested {public class NestedNameSpaceClass {public static voidSayHello()
            {
                Console.WriteLine("In Nested"); }}}}Copy the code

Preprocessor instruction

Preprocessor instructions instruct the compiler to preprocess the information before the actual compilation begins.

All preprocessor instructions begin with #, not with a semicolon (;). The end of the

The #define preprocessor instruction creates symbolic constants. Use the symbol as the expression passed to the #if directive, which returns true.

#define PI
using System;
namespace PreprocessorDAppl
{
   class Program
   {
      static void Main(string[] args)
      {
         #if (PI)
            Console.WriteLine("PI is defined");
         #else
            Console.WriteLine("PI is not defined");
         #endifConsole.ReadKey(); }}}Copy the code