当前位置:网站首页>C (I) C basic grammar all in one
C (I) C basic grammar all in one
2022-06-11 05:10:00 【Aaaaan】
C# It's from Microsoft (Microsoft) Developed , be based on C and C++ An object-oriented programming language , Its grammatical rules are very similar to Java, Commonly used for rapid development Windows Desktop application . This article will C# Some basic grammar knowledge for quick learning , Quick start .
One .C# Program structure
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace netBasic_learning
{
// The definition of a class
class Rectangle
{
//(1) attribute
double length;
double width;
//(2) Method
public void Acceptdetails()
{
this.length = 4.5;
this.width = 2;
}
public double getArea()
{
return this.length * this.width;
}
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", getArea());
}
//Main Function is the main entry of the program
public static void Main(string[] args)
{
Rectangle rectangle = new Rectangle();
rectangle.Acceptdetails();
rectangle.Display();
// Blocking windows
Console.ReadLine();
}
}
}
1.using Use :
(1) meaning : using namespace std , Be similar to Java Of Import
(2) Be careful :using Keyword is used to include the namespace... In the program . A program can contain more than one using sentence .2.namespace Use :
(1)namespace Declare the namespace of this class as netBasic_learning, Other places can go through using netBasic_learning To use the classes and methods here
(2) One namespace Can contain multiple classes3.Main Function blocking :
(1)Console.ReadLine() : The last line Console.ReadLine(); Is aimed at VS.NET User . This causes the program to wait for a carriage return , Prevent the program from Visual Studio .NET On startup, the screen will run quickly and close . That is to prevent the black window from flashing , Block up . meanwhile ReadLine() Method can also be used to read program input . (2)Console.ReadKey() : Its function is the same as above .
4. summary :
1.C# Grammar basic and Java almost , Both are object-oriented languages . It's just C# Mainly for desktop application development ,Java Main orientation Web application development
2.C# And Java The difference is , The filename can be different from the name of the class .
Two .C# Data types and variables
1. Basic data type

namespace netBasic_learning
{
class Basic_dataType
{
public static void Main(String[] args)
{
//1. Basic data type : Allocate storage space , Storing data
int Int_number = 1;
double Double_number = 3.14;
bool Bool_number = true;
Console.WriteLine("Int: {0},Double: {1},Bool: {2}", Int_number,Double_number,Bool_number);// Word wrap
}
}
}
2. Reference type
The reference type does not contain the actual data stored in the variable , But they contain references to variables . let me put it another way , They refer to a memory location . When using multiple variables , Reference types can point to a memory location . If the data of the memory location is changed by a variable , Other variables will automatically reflect the change of this value . Built in There are :object、string And our custom classes Class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace netBasic_learning
{
class Basic_dataType
{
public static void Main(String[] args)
{
// Reference data type : The reference address where the data is stored , Another name (Object、String、class)
String str = "Hello World!";
String str_origin = "Hello\nWorld!";// Escape character
String str_change = @"Hello\nWorld!";// Original output @ = "\\"
Console.WriteLine("String str: {0}", str);
Console.WriteLine("String str_origin: {0}", str_origin);
Console.WriteLine("String str_change: {0}", str_change);
}
}
}
3. Data type conversion
One . Data type conversion
(1) Implicit type conversion : Safe switching , No data loss . For example, from a derived class to a base class , Small range type -> Wide range of types int->long,float->double, In some calculations, automatic conversion occurs
(2) Explicit type conversion : Unsafe conversion , May cause data loss . such as double->int(3) Built in type conversion methods :int.Parse()、ToString() etc.
namespace netBasic_learning
{
class Basic_dataType
{
public static void Main(String[] args)
{
// Data type conversion
// (1) Implicit type conversion : Safe switching , No data loss . For example, from a derived class to a base class , Small range type -> Wide range of types int->long,float->double, In some calculations, automatic conversion occurs
// (2) Explicit type conversion : Unsafe conversion , May cause data loss . such as double->int
double a = 3.1415;
int b = (int)a;// Rounding down , Lost precision
Console.WriteLine("Double->Int: {0}", b);
// (3) Built in type conversion methods
string num = "66";
Console.WriteLine("Int -> String: {0}",a.ToString());
Console.WriteLine("String -> Int: {0}", int.Parse(num));
//4. Constant :const , Cannot be modified during operation
Console.ReadLine();
}
}
}
4. character string string type
One . character string : Use string Keyword to declare a string variable .string Keywords are System.String Alias of class .
1. String construction :
- "":string str = "hello world!";
- +:string str = a + b;( String splicing )2. String common methods :
- public static int Compare( string strA, string strB ): Compare two specified string object ( Press ASCII), And returns an integer representing their relative position in the arrangement order .
- public static string Concat( string str0, string str1 ): Connect two string object . amount to +
- public bool Contains( string value ): Determine whether the string contains a string value
- public bool EndsWith( string value ): Judge string Whether the object is in value ending .
- public bool StartsWith( string value ): Determines whether the beginning of the string instance matches the specified string .
- public bool Equals( string value ): Judge the current string Whether the object matches the specified string Object has the same value .
- public static string Format( string format, Object arg0 ): Replace one or more format items in the specified string with the string representation of the specified object .
- public int IndexOf( string value/char ch ): Returns the index of the first occurrence of the specified string in the instance , Index from 0 Start .
- public int LastIndexOf( string value/char value ): Returns the index of the last occurrence of the specified string in the instance , Index from 0 Start .
- public string Insert( int startIndex, string value ): Returns a new string , among , The specified string is inserted in the current string The specified index location of the object .
- public static string Join( string separator, string[] value ): Connect all elements in a string array , Separate each element with the specified separator .
- public string Remove( int startIndex ): Remove all characters in the current instance , Start at the specified location , Until the last position , And return a string .
- public string Replace( string oldValue, string newValue ): Put the present string In the object , All specified strings are replaced with another specified string , And return the new string .
- public string[] Split( params char[] separator ): Returns an array of strings , Include the current string Object , The substring is specified using Unicode Separated by elements in a character array .
- public char[] ToCharArray(): Returns a with the current string Of all characters in the object Unicode A character array .
- public string ToLower()/ToUpper()/Trim()
namespace netBasic_learning
{
class Basic_string
{
public static void mains(string[] args)
{
// (1) String construction :
string a_str = "Hello,";
string b_str = "World!,Write the code,change the world.";
string strs = a_str + b_str;
Console.WriteLine(strs);
/**
*(2) String method 、 operation ( a key ):
*/
//2. String comparison
string c_str = "Hello,";
if(a_str == c_str)//== In the quoted data , The comparison is the address . So two variables with the same data may be “ Unequal ”.
{
// But here it is the same , as a result of string Is a constant , The same address .
Console.WriteLine("== Comparative symbols :a_str And c_str identical ");
}
if (a_str.Equals(c_str))//Equals The comparison is whether the values are the same , recommend !
{
Console.WriteLine("Equals Comparison function :a_str And c_str identical ");
}
int res = String.Compare(a_str, b_str);//a_str<b_str Is the more <0;a_str=b_str yes =0;a_str>b_str yes >0
Console.WriteLine(" Sorting result : {0}",res);
//2. The string contains
if (strs.Contains("World"))
{
Console.WriteLine("{0} contain {1}", strs,"World");
}
//3. String acquisition
string child_str = strs.Substring(15);
Console.WriteLine(child_str);
//4. String merge
string[] str_arrays = { "hello", "world", "i'm", "OK" };
string join_str = String.Join("-", str_arrays);
Console.WriteLine(join_str);
//5. String segmentation
string[] str_list = join_str.Split('-');
foreach(string factor in str_list)
{
Console.WriteLine(factor);
}
//6. String formatting
Console.ReadKey();
}
}
}
3、 ... and .C# Calculations and conditions 、 loop
1. Calculation statement
1. Arithmetic operator :+、-、*、/、%、++、--
2. Relational operator :==、!=、>、<、>=、<=
3. Logical operators :&&、||、!
4. An operation :&( And , whole 1 only 1)、|( or , One 1 namely 1)、^( Exclusive or , Difference is 1)、<<( Move left , Right mend 0)、>>( Move right , Left complement 0)
5. Assignment operator :+=、-=、/=、%=、&=、<<=
6. Other operators :
(1)?: Ternary expression a==1?xxx:yyy
(2)& Address fetch
(3)* The pointer
(4)sizeof、typeof、is
namespace netBasic_learning
{
class Basic_calculate
{
public static void Main(string[] args)
{
// Arithmetic operations
double y = 5 / 2; // If / All methods are integers , The result of the operation is also an integer ( Rounding down )
double y_2 = 5.0/2;// If / Method has a floating point number , The result of the operation is automatically converted to a large type
Console.WriteLine(y);
Console.WriteLine(y_2);
// summary : Operation and Java almost -.-
Console.ReadLine();
}
}
}
2. To choice
One . conditional :
(1)if...else if...else
(2)switch(Expression){
case condition1:
break;
case condition2:
break;
default:
}
namespace netBasic_learning
{
class Basic_calculate
{
public static void Main(string[] args)
{
double y = 5 / 2; // If / All methods are integers , The result of the operation is also an integer ( Rounding down )
// conditional :
if (y>0)
{
Console.WriteLine("y > 0");
}else if (y == 0)
{
Console.WriteLine("y = 0");
}
else
{
Console.WriteLine("y < 0");
}
Console.ReadLine();
}
}
}
3. Loop branches
One . Loop statement
(1) for:for( initialization , Judge , Cyclic operation ){ Loop statement }、foreach()
(2) while: As long as the given condition is true , Will repeatedly execute a target statement . Judge before you execute
(3)do..while: Check its condition at the end of the loop . Will ensure that at least one loop is executed .
(4) Loop control statement :break Out of the loop ,continue Continue the cycle directly
namespace netBasic_learning
{
class Basic_calculate
{
public static void Main(string[] args)
{
// Loop statement
// (1)for:for( initialization , Judge , Cyclic operation ){ Loop statement }
// (2)while: As long as the given condition is true , Will repeatedly execute a target statement . Judge before you execute
// (3)do..while: Check its condition at the end of the loop . Will ensure that at least one loop is executed .
// (4) Loop control statement :break Out of the loop ,continue Continue the cycle directly
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
}
Console.ReadLine();
}
}
}
Four .C# Array
1. Null type
1. Null type (null): Nullable types can represent values in the normal range of their underlying value types , Add one more null value .
(1) Declare nullable type :
- The basic data :? A single question mark is used to int、double、bool Etc. cannot be directly assigned to null The data type of null Assignment . such as :int? num1 = null;
- Classes and objects : Make a direct statement(2)null coalescing operator (??): Judge if the value of the first operand is null, The operator returns the value of the second operand , Otherwise, return the value of the first operand .
- Use :a = b ?? c
- The essence :a = (b==null)?c:b
namespace netBasic_learning
{
class Basic_Arrays
{
public static void Main(string[] args)
{
//1. Null type (null): Nullable types can represent values in the normal range of their underlying value types , Add one more null value .
// (1) Declare nullable type :
int? num1 = null;// Can be empty int Type is null
int? num2 = 66;// Can be empty int Type does not take null value
double? num3 = null;
double? num4 = 3.1415;
Console.WriteLine(" Displays values of nullable types : {0}, {1}, {2}, {3}",num1, num2, num3, num4);
if(num1 == null)// A null value judgment
{
Console.WriteLine("Int data num1 Null value ");
}
Rectangle rect = null;// class & Object null declaration
if(rect == null)// class & Object null value judgment
{
Console.WriteLine("Rectangle Class object rect It's empty ");
}
// (2)null coalescing operator (??): Judge if the value of the first operand is null, The operator returns the value of the second operand , Otherwise, return the value of the first operand .
double? b = null;
double? c = 3.1415;
double? a = b ?? c;//b If it is empty, return c
Console.WriteLine("a Value : {0}", a);
Console.ReadKey();
}
}
}
2. Array
1. Array : An array is a store 【 Elements of the same type 】 A fixed size sequential set of
(1) Declaration array :double[] arrays; Declaring an array does not initialize the array in memory .
(2) Initialize array :double[] balance = new double[10]; Array is a reference type , So you need to use new Keyword to create an instance of the array .
(3) Array assignment :
- Index assignment : balance[0] = 3.14;
- Assign values to the array while declaring it : double[] balance = { 2340.0, 4523.69, 3421.0};
- Create and initialize an array : int [] marks = new int[5] { 99, 98, 92, 97, 95};
- Omit the size of the array :int [] marks = new int[] { 99, 98, 92, 97, 95};
- Assign an array variable to another target array variable . under these circumstances , The target and source will point to the same memory location ( quote ):int[] score = marks;
(4) The data access 、 Traverse :[] The subscript access +for、foreach loop(5) Multidimensional arrays :int[,] a; Declare a two-dimensional array ,int[, ,] a; Declare a three-dimensional array
(6) Jagged arrays : An interleaved array is an array of arrays . An interleaved array is a one-dimensional array , Each element is an array
- Statement :int [][] scores;int One dimensional array of arrays , Declaring an array does not create an array in memory
- initialization :int[][] scores = new int[5][]; There are five elements
- Initialize assignment :int[][] scores = new int[2][]{new int[]{92,93,94},new int[]{85,66,87,88}};
- visit :scores[i][j] Take the first place i The second... Of the subarray j Elements ( It's like a two-dimensional array )
namespace netBasic_learning
{
class Basic_Arrays
{
public static void Main(string[] args)
{
//1. Array : An array is a store 【 Elements of the same type 】 A fixed size sequential set of
// (1) Declaration array :double[] arrays; Declaring an array does not initialize the array in memory .
// (2) Initialize array :double[] balance = new double[10]; Array is a reference type , So you need to use new Keyword to create an instance of the array .
// (3) Array assignment :
// - Index assignment : balance[0] = 3.14;
// - Assign values to the array while declaring it : double[] balance = { 2340.0, 4523.69, 3421.0};
// - Create and initialize an array : int [] marks = new int[5] { 99, 98, 92, 97, 95};
// - Omit the size of the array :int [] marks = new int[] { 99, 98, 92, 97, 95};
// - Assign an array variable to another target array variable . under these circumstances , The target and source will point to the same memory location ( quote ):int[] score = marks;
// (4) The data access 、 Traverse :[] The subscript access +for、foreach loop
int[] List = new int[10];
for(int i = 0; i < List.Length; i++)
{
List[i] = i*2;
}
foreach(int j in List)
{
Console.WriteLine("Element = {0}",j);
}
// (4) Multidimensional arrays :int[,] a; Declare a two-dimensional array ,int[, ,] a; Declare a three-dimensional array
int[,] matrix = new int[3, 4];// initialization 3x4 Two dimensional array of
int[,] matrix_2 = new int[3, 4]{// Initialize and assign
{0,1,2,3 }, // Initializing page 0 That's ok
{4,5,6,7}, // Initializing page 1 That's ok
{8,9,10,11} // Initializing page 2 That's ok
};
for(int i = 0; i < matrix_2.GetLength(0); i++)// Loop through multidimensional arrays
{
for(int j = 0; j < matrix_2.GetLength(1); j++)
{
Console.WriteLine(" matrix ({0},{1}) The value of is {2}", i,j, matrix_2[i,j]);
}
}
// (5) Jagged arrays : An interleaved array is an array of arrays . An interleaved array is a one-dimensional array , Each element is an array
// - Statement :int [][] scores;int One dimensional array of arrays , Declaring an array does not create an array in memory
// - initialization :int[][] scores = new int[5][]; There are five elements
// - Initialize assignment :int[][] scores = new int[2][]{new int[]{92,93,94},new int[]{85,66,87,88}};
// - visit :scores[i][j] Take the first place i The second... Of the subarray j Elements ( It's like a two-dimensional array )
int[][] scores = new int[5][];
for (int i = 0; i < scores.Length; i++)
{
if (i <= 2) scores[i] = new int[3];
else scores[i] = new int[5];
for(int j = 0; j < scores[i].Length; j++)
{
scores[i][j] = i * j + 6;
}
}
for (int i = 0; i < scores.Length; i++)
{
for (int j = 0; j < scores[i].Length; j++)
{
Console.WriteLine(" Subarray {0} Subscript {1} The value of is {2}", i, j, scores[i][j]);
}
}
Console.ReadKey();
}
}
}
(7)Array class :Array Class is C# The base class for all arrays in , Provides many properties and methods
- Array.Clear: Depending on the type of element , Set the element of a range in the array to zero 、 by false Or for null.
- Array.IndexOf(Array, Object): Search for the specified object , Back to the whole [ One dimensional array ] The first index in .
- Array.Reverse(Array): Reverse the order of elements in an entire one-dimensional array .
- Array.Sort(Array): Use the... Of each element of the array IComparable Implement to sort the elements of the entire one-dimensional array .
namespace netBasic_learning
{
class Basic_Arrays
{
public static void Main(string[] args)
{
// (6)Array class :Array Class is C# The base class for all arrays in , Provides many properties and methods
// - Array.Clear: Depending on the type of element , Set the element of a range in the array to zero 、 by false Or for null.
// - Array.IndexOf(Array, Object): Search for the specified object , Back to the whole [ One dimensional array ] The first index in .
// - Array.Reverse(Array): Reverse the order of elements in an entire one-dimensional array .
// - Array.Sort(Array): Use the... Of each element of the array IComparable Implement to sort the elements of the entire one-dimensional array .
int[] list = { 34, 72, 13, 44, 25, 30, 10 };
Console.Write(" The original array : ");
foreach (int i in list)
{
Console.Write(i + " ");// Don't wrap output
}
Console.WriteLine();// Output line feed
// Reverse array
Array.Reverse(list);// Change the original array
Console.Write(" Reverse array : ");
foreach (int i in list)
{
Console.Write(i + " ");
}
Console.WriteLine();
// Sort array
Array.Sort(list);// Change the original array , Default from small to large
Console.Write(" Sort array : ");
foreach (int i in list)
{
Console.Write(i + " ");
}
Console.ReadKey();
}
}
}
5、 ... and . Lists and dictionaries
1. list ArrayList
1.ArrayList: Dynamic array list collection , Be similar to Java Of List<Object>
(1) initialization :ArrayList Is a class / object , Need to use new Keyword initialization , And there is no need to specify the size ( Dynamic expansion ) ArrayList array = new ArrayList();
(2) characteristic :
- Dynamic extension of length , There is no need to specify ;
- Use when storing data Object type , So it can store many different data at the same time (int、double、class、string)
- Not type safe , Type matching errors may occur ; There are frequent packing and unpacking operations , Poor performance
(3) Use :
- Item[Int32] Gets or sets the element at the specified index .
- Count obtain ArrayList Number of elements actually contained in .
- public virtual int Add( object value ); stay ArrayList Add an object at the end of .
- public virtual void Clear(); from ArrayList Remove all elements from .
- public virtual void Insert( int index, object value ); stay ArrayList At the specified index of , Insert an element .
- public virtual void Remove( object obj ); from ArrayList Remove the first occurrence of the specified object .
namespace netBasic_learning
{
//1.ArrayList: Dynamic array list collection , Be similar to Java Of List<Object>
class ArrayList_Use
{
public static void mains(string[] args)
{
ArrayList arrayList = new ArrayList();
arrayList.Add(2);
arrayList.Add(3.1415);
arrayList.Add("hello world");
Console.WriteLine("ArrayList length : " + arrayList.Count);
Console.WriteLine("ArrayList[0]: " + arrayList[0]);
Console.WriteLine("ArrayList[1]: " + arrayList[1]);
Console.WriteLine("ArrayList[2]: " + arrayList[2]);
Console.ReadKey();
}
}
}2. list List
2.List:List It is also a dynamic list collection , Be similar to ArrayList, But you must provide generics
(1) Definition : In order to solve ArrayList The type of is not safe ,C# Provides List list ,List A generic type must be provided when declaring a list , namely List The stored data must be the data of the generic type .
(2) initialization :List<int> list = new List<int>();
(3) The essence :List In fact, in the ArrayList On the basis of , Added type restrictions , It is recommended to use in the future List
(4) Use : And ArrayList similar , Note that generics can also be custom classes ,List You can also store objects !
namespace netBasic_learning
{
//2.List:List It is also a dynamic list collection , Be similar to ArrayList, But you must provide generics
// (1) Definition : In order to solve ArrayList The type of is not safe ,C# Provides List list ,List A generic type must be provided when declaring a list , namely List The stored data must be the data of the generic type .
// (2) initialization :List<int> list = new List<int>();
// (3) The essence :List In fact, in the ArrayList On the basis of , Added type restrictions , It is recommended to use in the future List
// (4) Use : And ArrayList similar , Note that generics can also be custom classes ,List You can also store objects !
class List_Use
{
public static void mains(string[] args)
{
List<int> list = new List<int>();
for(int i = 0; i < 10; i++)
{
list.Add(i + 1);
}
for(int i = 0; i < list.Count; i++)
{
if (list[i] % 2!=0)
{
list[i] *= 2;
}
}
foreach(int val in list)
{
Console.Write(val + " ");
}
Console.WriteLine();
list.Clear();
Console.WriteLine(" Length after emptying : " + list.Count);
Console.ReadLine();
}
}
}
3. Dictionaries Dictionary
3.Dictionary:Dictionary Is a dictionary type consisting of key value pairs , Be similar to Java Of Map
(1) initialization :Dictionary Also object , Need to use new keyword . At the same time, you need to specify the generic type of key value pair during initialization Dictionary<string,int> dir = new Dictionary<string,int>();
(2) characteristic :
- Dictionary Every element in it is a key value pair ( It's made up of two elements : Key and value ), Can pass Dictionary[key] To take a value
- Dictionary The inner key must be unique , And values don't need to be unique
(3) Use :
- Count Get included in Dictionary<TKey, TValue> The key / The right number .
- Keys Get contains Dictionary<TKey, TValue> The set of keys in .
- Values Get contains Dictionary<TKey, TValue> The set of values in .
- Add Adds the specified key and value to the dictionary .
- Clear from Dictionary<TKey, TValue> Remove all keys and values from .
- ContainsKey determine Dictionary<TKey, TValue> Whether to include the specified key .
- GetEnumerator Return to loop access Dictionary<TKey, TValue> The enumerator of
- Remove from Dictionary<TKey, TValue> Remove the value of the specified key from the .
namespace netBasic_learning
{
//3.Dictionary:Dictionary Is a dictionary type consisting of key value pairs , Be similar to Java Of Map
// (1) initialization :Dictionary Also object , Need to use new keyword . At the same time, you need to specify the generic type of key value pair during initialization Dictionary<string,int> dir = new Dictionary<string,int>();
// (2) characteristic :
// - Dictionary Every element in it is a key value pair ( It's made up of two elements : Key and value ), Can pass Dictionary[key] To take a value
// - Dictionary The inner key must be unique , And values don't need to be unique
// (3) Use :
// - Count Get included in Dictionary<TKey, TValue> The key / The right number .
// - Keys Get contains Dictionary<TKey, TValue> The set of keys in .
// - Values Get contains Dictionary<TKey, TValue> The set of values in .
// - Add Adds the specified key and value to the dictionary .
// - Clear from Dictionary<TKey, TValue> Remove all keys and values from .
// - ContainsKey determine Dictionary<TKey, TValue> Whether to include the specified key .
// - GetEnumerator Return to loop access Dictionary<TKey, TValue> The enumerator of
// - Remove from Dictionary<TKey, TValue> Remove the value of the specified key from the .
class Dictionary
{
public static void Main(string[] args)
{
Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary.Add("wangxin", 99);//Add assignment ,Add Assignment cannot be added key Duplicate items
dictionary["shayuan"] = 100;//= assignment ,= Assignment can add key Duplicate item , Will overwrite the original data
if (dictionary.ContainsKey("wangxin"))// Does it include key
{
Console.WriteLine("Dictionary length : " + dictionary.Count);
Console.WriteLine("wangxin is {0}", dictionary["wangxin"]);
dictionary.Remove("wangxin");// Delete key
}
if (dictionary.ContainsKey("shayuan"))
{
Console.WriteLine("Dictionary length : " + dictionary.Count);
Console.WriteLine("shayuan is {0}", dictionary["shayuan"]);
}
//Console.WriteLine("wangxin is {0}", dictionary["wangxin"]);// Accessing nonexistent data will result in an exception
if (!dictionary.ContainsKey("wangxin"))
{
Console.WriteLine("wangxin is removed!");
}
// Traverse Dictionary
// Traverse key
foreach (string key in dictionary.Keys)
{
Console.WriteLine("Key = {0}", key);
}
// Traverse value
foreach (int value in dictionary.Values)
{
Console.WriteLine("value = {0}", value);
}
// Ergodic dictionary
foreach (KeyValuePair<string, int> kvp in dictionary)
{
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
// Add existing elements try...catch.. Handling exceptions
try
{
dictionary.Add("txt", 99);
}
catch (ArgumentException)
{
Console.WriteLine("An element with Key = \"txt\" already exists.");
}
Console.ReadKey();
}
}
}
6、 ... and . Class to inherit
1. The basic concept of class
1. Class encapsulation
(1) Access modifier : The default access identifier of the class is internal, The default access identifier for a member is private.
- public: All objects can access ;
- private: The object itself can be accessed inside the object ;
- protected: Only objects of this class and its subclasses can access
- internal: Objects of the same assembly can access ; Can be defined in the 【 In app 】 Any class or method access .
- protected internal: Access is limited to the current assembly or type derived from the containing class .(protected and internal Union )
(2) Method : Class , It mainly refers to the transfer method of method parameters
- Value passed : In this way, the actual value of the parameter is copied to the formal parameter of the function , Arguments and formal parameters use two different values in memory . under these circumstances , When the value of a formal parameter changes , Does not affect the value of the argument
- reference (ref): In this way, the reference of the memory location of the parameter is copied to the formal parameter . It means , When the value of a formal parameter changes , It also changes the value of the argument .
- Output parameters (out): Multiple values can be returned in this way . Pass on out When the defined parameter goes in, the parameter must be initialized inside the function . Otherwise, it cannot be compiled .
- Array pass value : You can pass a pointer to an array to a function by specifying an array name without an index .
Be careful :ref and out All the data is transferred to , Because of the address , To modify the source data .2. Basic parameters of class
(1) Constructors : Automatically execute when initializing an object , A parameterless construct is provided by default Object(){}
(2) Destructor : Automatically execute when destroying objects ~Object(){}
(3) Static member variable : static Keyword defines a class member as static , Static member variables belong to class , Can be initialized and used anywhere
(4) Static member functions :static Keyword defines a class member as static , Static member variables belong to class , Static member functions can only access static variables
namespace netBasic_learning
{
//1. Class encapsulation
// (1) Access modifier : The default access identifier of the class is internal, The default access identifier for a member is private.
// - public: All objects can access ;
// - private: The object itself can be accessed inside the object ;
// - protected: Only objects of this class and its subclasses can access
// - internal: Objects of the same assembly can access ; Can be defined in the 【 In app 】 Any class or method access .
// - protected internal: Access is limited to the current assembly or type derived from the containing class .(protected and internal Union )
// (2) Method : Class , It mainly refers to the transfer method of method parameters
// - Value passed : In this way, the actual value of the parameter is copied to the formal parameter of the function , Arguments and formal parameters use two different values in memory . under these circumstances , When the value of a formal parameter changes , Does not affect the value of the argument
// - reference (ref): In this way, the reference of the memory location of the parameter is copied to the formal parameter . It means , When the value of a formal parameter changes , It also changes the value of the argument .
// - Output parameters (out): Multiple values can be returned in this way . Pass on out When the defined parameter goes in, the parameter must be initialized inside the function . Otherwise, it cannot be compiled .
// - Array pass value : You can pass a pointer to an array to a function by specifying an array name without an index .
// Be careful :ref and out All the data is transferred to , Because of the address , To modify the source data .
class A
{
public int _a;
public int _b;
// Value passed
public void sum(int a,int b)
{
a += b;
Console.WriteLine(" Sum in value transfer function a = {0}", a);
}
// reference
public void sum(ref int a,ref int b)
{
a += b;
Console.WriteLine(" Sum inside the reference transfer function a = {0}", a);
}
// Output parameters
public void sum(int a,int b,out int c)
{
c = a + b;
}
// class / Object delivery ( Object value transfer = Pass value by reference )
public void swap(A obj)
{
int temp = obj._a;
obj._a = obj._b;
obj._b = temp;
}
// Array pass value
public void sumAndClear(int[] arrays)
{
int sum = 0;
for(int i = 0; i < arrays.Length; i++)
{
sum += arrays[i];
arrays[i] = 0;
}
Console.WriteLine(" Array sum sum = {0}", sum);
}
public static void Main(string[] args)
{
A a_obj = new A();
// Value passed
int a = 3, b = 4;
Console.WriteLine(" Value transfer initial data before summation a = {0},b = {1}", a,b);
a_obj.sum(a, b);
Console.WriteLine(" Initial data after summation of value transfer a = {0},b = {1}", a, b);
// reference
Console.WriteLine(" Reference passes the initial data before summation a = {0},b = {1}", a, b);
a_obj.sum(ref a, ref b);
Console.WriteLine(" The initial data after the sum is passed by reference a = {0},b = {1}", a, b);
// Output parameters
int res;
Console.WriteLine(" Output initial data before parameter summation a = {0},b = {1}", a, b);
a_obj.sum( a, b,out res);
Console.WriteLine(" The initial data after the sum is passed by reference a = {0},b = {1},res = {2}", a, b,res);
// Object delivery
a_obj._a = 3;
a_obj._b = 4;
Console.WriteLine(" The object passes the initial data before exchange a = {0},b = {1}", a_obj._a, a_obj._b);
a_obj.swap(a_obj);
Console.WriteLine(" Object transfers the initial data after exchange a = {0},b = {1}", a_obj._a, a_obj._b);
// Array passing
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Console.Write(" Before array value transfer : ");
foreach(int fac in arr) Console.Write(fac + " ");
Console.WriteLine();
a_obj.sumAndClear(arr);
Console.Write(" After the array passes values : ");
foreach (int fac in arr) Console.Write(fac + " ");
Console.ReadLine();
}
}
//2. Basic parameters of class
// (1) Constructors : Automatically execute when initializing an object , A parameterless construct is provided by default Object(){}
// (2) Destructor : Automatically execute when destroying objects ~Object(){}
// (3) Static member variable : static Keyword defines a class member as static , Static member variables belong to class , Can be initialized and used anywhere
// (4) Static member functions :static Keyword defines a class member as static , Static member variables belong to class , Static member functions can only access static variables
class B
{
public static int cnt = 0;
private double val;
public B()
{
val = 0;
cnt++;
Console.WriteLine(" The first {0} individual B, Parameter free constructor Val = {1}",cnt,val);
}
public B(double _val = 0)
{
val = _val;
cnt++;
Console.WriteLine(" The first {0} individual B, There are parameter constructors Val = {1}", cnt,val);
}
public double getVal()
{
return this.val;
}
public static int getCntOfB()
{
return cnt;
}
~B()
{
cnt--;
Console.WriteLine(" The destructor executes ");
}
public static void Main(string[] args)
{
B b_1 = new B();
Console.WriteLine(b_1.getVal());
B b_2 = new B(3.14);
Console.WriteLine(b_2.getVal());
Console.WriteLine(B.getCntOfB());
Console.ReadKey();
}
}
}
2. Class inheritance
3. Class inheritance Child:Parent
(1)C# Only single inheritance is supported , But multiple inheritance can be implemented through interfaces
(2) Derived classes inherit the base class's public、protected、internal Member variables and member methods .
(3) If not specified , When you create a subclass object and call the subclass constructor , The parameterless constructor of the parent class will be called first by default
namespace netBasic_learning
{
//3. Class inheritance Child:Parent
// (1)C# Only single inheritance is supported , But multiple inheritance can be implemented through interfaces
// (2) Derived classes inherit the base class's public、protected、internal Member variables and member methods .
// (3) If not specified , When you create a subclass object and call the subclass constructor , The parameterless constructor of the parent class will be called first by default
class Shape
{
protected double length;
protected double width;
public Shape(double len,double wid)
{
length = len;
width = wid;
}
public double GetArea()
{
return length * width;
}
public void Display()
{
Console.WriteLine(" length : {0}", length);
Console.WriteLine(" Width : {0}", width);
Console.WriteLine(" area : {0}", GetArea());
}
}
class Cube:Shape
{
private double height;
public Cube(double len,double wid,double hei): base(len, wid)//base(x,y) Initialize parent class parameters , Execute before subclass
{
height = hei;
}
public double GetVolume()
{
return height * GetArea();
}
public void Display()
{
base.Display();// adopt base To refer to the parent class of the current object
Console.WriteLine(" Volume : {0}", GetVolume());
}
public static void Main(string[] args)
{
Cube cube = new Cube(2, 3, 4);
cube.Display();// Call the override method of the subclass
Console.ReadKey();
}
}
}
7、 ... and . many state
1. polymorphic : Polymorphism is the ability of the same behavior to have multiple different forms or forms according to different scenarios .
(1) Static polymorphism : Function response occurs at compile time .
- function overloading : There are multiple definitions of the same function name . It can be that the parameter types in the parameter list are different , It can also be that the number of parameters is different . Cannot overload function declarations with only different return types .
- Operator overloading : Can redefine or overload C# The operators built into . By keyword operator Defined by the symbol followed by the operator , Also include public and static Modifier .
namespace netBasic_learning
{
//1. polymorphic : Polymorphism is the ability of the same behavior to have multiple different forms or forms according to different scenarios .
// (1) Static polymorphism : Function response occurs at compile time .
// - function overloading : There are multiple definitions of the same function name . It can be that the parameter types in the parameter list are different , It can also be that the number of parameters is different . Cannot overload function declarations with only different return types .
// - Operator overloading : Can redefine or overload C# The operators built into . By keyword operator Defined by the symbol followed by the operator , Also include public and static Modifier .
class Vector
{
private int x;
private int y;
public Vector()
{
x = 0;
y = 0;
}
public Vector(int _x,int _y)
{
x = _x;
y = _y;
}
public int getX() { return x; }
public int getY() { return y;}
public void setX(int x) { this.x = x; }
public void setY(int y) { this.y = y; }
public void Display()
{
Console.WriteLine("Vector({0},{1})", x, y);
}
// heavy load + Operator to put two Vector Add objects ( You can directly access private)
public static Vector operator +(Vector a, Vector b)
{
Vector C = new Vector();
C.x = a.x + b.x;
C.y = a.y + b.y;
return C;
}
// heavy load - Operator to put two Vector Object subtraction ( You can directly access private)
public static Vector operator -(Vector a, Vector b)
{
Vector C = new Vector();
C.x = a.x - b.x;
C.y = a.y - b.y;
return C;
}
// heavy load * Operator to put two Vector Multiply objects ( You can directly access private)
public static int operator *(Vector a, Vector b)
{
return a.x * b.x + a.y * b.y;
}
public static void Main(string[] args)
{
Vector a = new Vector(2, 3);
Vector b = new Vector(3, 4);
//+ Law
Vector c = a + b;
c.Display();
//- Law
c = a - b;
c.Display();
//* Law
int res = a * b;
Console.WriteLine(res);
Console.ReadKey();
}
}
}(2) Dynamic polymorphism : The response of the function occurs at run time .
- Virtual method (virtual ): Defining a subclass can override methods that override the parent class , The call to a virtual method occurs at run time . Subclasses need to use override Statement
+ The parent class defines the virtual method , Subclasses can override the virtual methods of the parent class , It is also possible not to implement rewriting . If I rewrite it , After creating the subclass object , Whether it's a parent class pointer or a subclass , Calling virtual methods will perform the override of subclasses .
+ The parent class defines the virtual method , There must be an implementation of the parent class , It is a normal function in the parent class .
- abstract (abstract ): abstract abstract Keywords can act on methods , It can also work on classes . Subclasses need to use override Statement
+ The parent class abstract method does not implement , Only the statement . The subclass must implement the abstract method of the parent class
+ Any method in a class is abstract , The class must be declared as an abstract class . That is, abstract methods can only be defined in abstract classes
+ Abstract class cannot be instantiated , But it can point to subclass instances . Subclasses that do not implement abstract methods will also become abstract classes .
- summary : In short , Abstract methods need subclasses to implement . Virtual methods are already implemented , Can be overridden by subclasses , You can also not cover , Depends on demand . Both abstract and virtual methods can be overridden by derived classes .
namespace netBasic_learning
{
// Dynamic polymorphism : The response of the function occurs at run time .
// - Virtual method (virtual ): Defining a subclass can override methods that override the parent class , The call to a virtual method occurs at run time . Subclasses need to use override Statement
// + The parent class defines the virtual method , Subclasses can override the virtual methods of the parent class , It is also possible not to implement rewriting . If I rewrite it , After creating the subclass object , Whether it's a parent class pointer or a subclass , Calling virtual methods will perform the override of subclasses .
// + The parent class defines the virtual method , There must be an implementation of the parent class , It is a normal function in the parent class .
// - abstract (abstract ): abstract abstract Keywords can act on methods , It can also work on classes . Subclasses need to use override Statement
// + The parent class abstract method does not implement , Only the statement . The subclass must implement the abstract method of the parent class
// + Any method in a class is abstract , The class must be declared as an abstract class . That is, abstract methods can only be defined in abstract classes
// + Abstract class cannot be instantiated , But it can point to subclass instances . Subclasses that do not implement abstract methods will also become abstract classes .
// - summary : In short , Abstract methods need subclasses to implement . Virtual methods are already implemented , Can be overridden by subclasses , You can also not cover , Depends on demand . Both abstract and virtual methods can be overridden by derived classes .
abstract class Animal
{
// abstract class : Contains at least one abstract method , But it's not just about abstract methods
protected string name;
public Animal(string _name)
{
name = _name;
}
// Abstract method : It's called
abstract public void shout();
// Virtual method
virtual public void eat()
{
Console.WriteLine("{0} is eating",name);
}
}
class Dog : Animal
{
public Dog(string name):base(name)
{
}
// Implementing abstract classes
public override void shout()
{
Console.WriteLine("A Dog {0} is wangwang",name);
}
// Override override virtual function
public override void eat()
{
base.eat();
Console.WriteLine("A Dog {0} is eat bone", name);
}
}
class Cat : Animal
{
public Cat(string name) : base(name)
{
}
// Implementing abstract classes
public override void shout()
{
Console.WriteLine("A Cat {0} is miaomiao", name);
}
// Override override virtual function
public override void eat()
{
base.eat();
Console.WriteLine("A Cat {0} is eat fish", name);
}
public static void Main(string[] args)
{
Animal[] animals = new Animal[2] { new Dog("tom"), new Cat("marry") };
foreach(Animal animal in animals)
{
animal.shout();
animal.eat();
}
Console.ReadKey();
}
}
}
2. Interface (interface): Interfaces are similar to abstract classes , But all the methods in the interface are abstract
(1) Interface cannot be instantiated , Inherited interfaces must implement all abstract methods ( Don't declare override), Interfaces can point to subclasses ( polymorphic )
(2) The interface is declared as public
(3) Interfaces can inherit more , solve C# The inner class can inherit multiple base classes at the same time .
(4) Interface can inherit interface
namespace netBasic_learning
{
//2. Interface (interface): Interfaces are similar to abstract classes , But all the methods in the interface are abstract
// (1) Interface cannot be instantiated , Inherited interfaces must implement all abstract methods ( Don't declare override), Interfaces can point to subclasses ( polymorphic )
// (2) The interface is declared as public
// (3) Interfaces can inherit more , solve C# The inner class can inherit multiple base classes at the same time .
// (4) Interface can inherit interface
interface Parent
{
void disPlay();
}
class Child : Parent
{
public void disPlay()
{
Console.WriteLine("child is display!");
}
}
}
边栏推荐
- Google drive download failed, network error
- Apply the intelligent OCR identification technology of Shenzhen Yanchang technology to break through the bottleneck of medical bill identification at one stroke. Efficient claim settlement is not a dr
- Inventory | ICLR 2022 migration learning, visual transformer article summary
- Dongmingzhu said that "Gree mobile phones are no worse than apple". Where is the confidence?
- KD-Tree and LSH
- The programmers of a large factory after 95 were dissatisfied with the department leaders, and were sentenced for deleting the database and running away
- 工具类ObjectUtil常用的方法
- C language test question 3 (advanced program multiple choice questions _ including detailed explanation of knowledge points)
- Carrier coordinate system inertial coordinate system world coordinate system
- 华为设备配置跨域虚拟专用网
猜你喜欢

The solution "no hardware is configured for this address and cannot be modified" appears during botu simulation

Lianrui: how to rationally see the independent R & D of domestic CPU and the development of domestic hardware

Vins fusion GPS fusion part

JVM tuning V: JVM tuning tools and tuning practice

选择数字资产托管人时,要问的 6 个问题

IOU series (IOU, giou, Diou, CIO)

mysql字符串转数组,合并结果集,转成数组

Restoration of binary tree -- number restoration

Sealem Finance打造Web3去中心化金融平台基础设施

华为设备配置跨域虚拟专用网
随机推荐
Anaconda installation and use process
华为设备配置跨域虚拟专用网
Section II: structural composition characteristics of asphalt pavement (2) structural layer and performance requirements
Paper reproduction: expressive body capture
Use acme SH automatically apply for a free SSL certificate
Opencv learning path (2-2) -- Deep parsing namedwindow function
Take stock of the AI black technologies in the Beijing Winter Olympic Games, and Shenzhen Yancheng Technology
NVIDIA SMI has failed because it could't communicate with the NVIDIA driver
Simple linear regression of sklearn series
2020-12-24
Inventory | ICLR 2022 migration learning, visual transformer article summary
Titanic rescued - re exploration of data mining (ideas + source code + results)
KD-Tree and LSH
lower_ Personal understanding of bound function
About custom comparison methods of classes and custom methods of sort functions
董明珠称“格力手机做得不比苹果差”哪里来的底气?
Huawei equipment configuration MCE
Use of mmdetection
Yolov5 training personal data set summary
Support vector machine -svm+ source code