Comprehensive summary of C# knowledge points

I found a U3D internship and uploaded my previous notes.

C# study notes

basic grammar

Common Data Types

The initialization still needs to be initialized.

typeof gets the data type, this is often used for classes

Integer type: int(Int32), uint, long(int64), ulong, short, ushort

Floating point numbers: float, double, decimal

Other: bool, string, char

Commonly used escape sequences (same as c++): \\ , \n , \" etc.

Note: strings are reference types and other types are value types, you can use @ to contain a complete string to avoid escaping

@"c:\pro\a.exe"
"c:\\pro\\a.exe"

data conversion

Different from c++: up conversion is allowed, down conversion must Convert.XXX display conversion

int i=10;
double j=10;
i=(int)j  //i=Convert.ToInt32(j);
注意unchecked可检查溢出

complex data type

enumerate

enum :{

n1=0;

​ …

}

enum color:int{
    red,blue,yellow
}
枚举当中的数字,字符,以及其对应的值是可以相互转换的
color c=0 //表示是red

structure

shipping priority

similar to c++

^XOR

~ bitwise negation

The default operator can be used to generate the default value of the type default T can call the default constructor of T to return an object

namespace

Similar to packages in java, there can be multiple namespaces in a namespace,

When calling each other between different namespaces, you need to bring the namespace and use the content in it through the reference symbol.

The same namespace (by default all code is in the global space) is directly referenced by name

usage of using

  1. For the class library linked to the project, use using to import (using can only be followed by the class library)
  2. Aliases can be defined for the same class in different namespaces eg/ using timers=System.Timers ( only with classes )
  3. using static static class name No need to import static class name when using static class method in module
  4. Similar to the with (context manager) in python, it can implicitly release some resources (that is, call the Dispose function)

branch loop

array

rectangular array

[] =new [SIZE] SIZE here must be a constant

Common initialization techniques

const int size=5;
int[] arrays=new int[size]{1,2,3,4,5};
int[] arrays_2=new int[size];
int[] arrays_3={1,2,3,4,5};

multivariate rectangular array

[,…] name

Common initialization techniques

int[,] arrays=new int[3,2]{
   
   {1,2},{3,4},{5,6}};
//其余两种同上

jagged array

[][] name=new [size][] always only initialize the first dimension, and then initialize again

int[][] a=new int[SIZE][]//如果要初始化接下来每个数组的行,则需要每次都new新的行
int[][] b={
	new int[]{1,2},
	new int[]{1,2,3},
	....
}

If these numerical arrays do not initialize the value and only declare the size, then the default is 0

Zigzag arrays store arrays, while rectangular arrays store elements, so the type of foreach will be different

Common interfaces for arrays

.Length

foreach(name in arrays){...} Note that zigzag arrays and rectangular arrays are different in traversal . When using foreach to traverse the contents of the array, the original content cannot be modified.

string

Strings in c# are regarded as objects, and can also be regarded as char array (read-only) reference types

common interface

Length
Replace
Split
Trim
Contains str1.Contains(str2)
PadLeft/Right
ToLower/Upper
两个复制函数
stk1.CopyTo(stk2,i) 从第i个元素将stk1复制到stk2中,这种方式复制不创建新的对象
stk.Clone()返回一个用于复制的object对象
str1.CompareTo(str2)
//字符串的格式化处理
//通用格式为string.Format("{index:type小数点位数}",1,2,...)其后可以接受任意数量参数
string.Format("{0:C2}",1)//表示对1这个数组保留两位小数点,作货币格式输出

common interface

1.控制台输入输出
Console.WritenLine($"{变量名称}这之外的是一般字符串") //其中也可以进行运算 类似printf
Console.ReadLine();//与python类似 输入的数据一定是string要进行转换
2.数据类型转换
Convert.ToChar(int v)//这个v必须是对应的ascall值
Convert.ToCharArray(string str)
3.Object常用方法
.ToString()返回类名 类似于.GetType()

function

Base

fun_name( par)

parameter list

Parameters that can accept arbitrary parameters, need to use the keyword params

<type> fun(<type> name,params<ype>[] name)
void show(int bz,params int[] a)
//params的关键字必须放在函数签名的最后

In C#, value parameters are used by default (except for arrays, which can be regarded as using reference types), and value parameters can also be assigned default values

Two kinds of reference parameter keywords ref (must be initialized outside the function), out (must be initialized inside the function and discard the original value). These two keywords must be marked no matter when the function is defined or used

C# variable scope: depends on where it is initialized rather than where it is declared . Variables in C# are initialized when they are declared

For global data in C#, set a static class and give static variables in it

Overloading and struct functions are the same as other

Main is used as an entry and its signature is static void Main(string[] args). This args can be set in the debug option as a command line parameter

entrust

Similar to function pointers, keyword delegate

After the delegate type function(type par…) is declared, the delegate becomes a function type, and all functions conforming to the signature of the delegate can be assigned to the delegate variable, which can often be used as a function parameter, which is very convenient to use in the process of upward transformation (eg .c++ stl sort)

Taking sorting as an example, create a sorting that can customize the keyword method

delegate bool compare(int a,int b);
static void sort(int[] arrays,compare cp)
{
    int temp = 0;
    int j = 0;
    for (int i = 1; i < arrays.Length; i++)
    {
        if(!cp(arrays[i-1],arrays[i]))
        {
            temp = arrays[i];
            for (j = i; j > 0 && !cp(arrays[j-1],temp); j--)
                arrays[j] = arrays[j-1];
            arrays[j] = temp;
        }  
    }
}
static bool upper(int a,int b)=>a < b ? true : false; 
static bool lower(int a, int b) => a > b ? true : false;
//这是一种快捷的函数表述法

The delegate can also be used to implement the anonymous method
delegate(type1 a,type2 b){

​ ... There can be a return value (similar to function(){} in js)

}

object oriented

Base

Properties and Fields in C#

Attributes are different from fields. Attributes do not provide direct access to data and need to rely on certain interfaces. Fields can be accessed directly (if set to public)

Permissions: public, private, protected, internal (internal members, which means only members that can be used by this project, can be used in conjunction with protected, and can also modify classes), static

method (member function)

object life cycle

constructor-in-use-destructor (similar to C++),

Calling the constructor is to call the base class constructor first and complete the initialization sequentially from top to bottom

After calling the destructor, it will be called up in turn until it reaches the Finalize() function of the Object object

public class student{}
student std=new student();//这个括号不能省去

Static classes and static members

Static members are shared by all instances of the class

Static constructors (cannot have access qualifiers and parameters) are specially used to process static members of a class and are called only once, and can often be used to process singleton patterns

If you need to include only static members in a class (such as Console), you can use a static class, which can only contain static members, and the constructor can only have one static constructor. Static classes cannot be instantiated

Static functions can only call static functions and cannot call other member functions

The difference between a class and a structure : the declaration structure is a value type and the declaration object is a reference type, and there will be problems when the two are copied. Reference types are copied using shallow copying, and value types are using deep copying.

Solution to Deep and Shallow Copy Problem

Problems with shallow copying due to references

public class school
{
    public string name;
}
public class student
{
    public school sch;
    public string name;
    public student()
    {
        sch = new school();
    }
}
class Program
{
    static void Main(string[] args)
    {
        student std1 = new student();
        std1.name = "hjh";
        std1.sch.name = "smu";
        Console.WriteLine("修改前" + std1.name + " " + std1.sch.name);

        student std2 = std1;
        std2.sch.name = "fdu";
        Console.WriteLine("修改后" + std1.name + " " + std1.sch.name);//修改std2却修改了std1
    }
}

The value type defaults to deep copy, and the reference type is shallow copy (ps array)

field definition

public class name{
	public typename name;
}

Commonly used keywords for defining fields: const, static (these two keywords can define fields as read-only, and static fields can only be accessed through class names ), readonly (so that fields can only be initialized and assigned in constructors)

method definition

Commonly used keywords for defining fields: virtual, abstract (pure virtual function), override (you must use this keyword if you want to rewrite the object), extern, sealed (this keyword can be followed by override to indicate that it cannot be rewritten further)

public abstract class people{
	public abstract void show();//在抽象类中只有抽象函数可以只有定义
}
public sealed class student:people 
{
	public override void show(){}
}

Fields in c# can be given an initial value at the time of definition

define properties

It is equivalent to providing an interface for interacting with the outside world for the private fields inside the class

permission type name {

​ [Permission] get{return a private field}

​ [Privilege] set{a private field=value} value is used as a keyword to represent the value given by the user

}

The attribute must have one of get or set

private string name
public int Name{
	get{
		return name;
	}
	set{
		name=value;
	}
	//对于简单的字段可以直接用=>表达式eg.get=>name set set=>name=value
	//c#提供了快速重构方法
}

Attributes can also use method modifiers including virtual, abstract, override

Accessors cannot have higher permissions than the property itself

Automatic properties, only define the property interface but not define the private data it operates, essentially hiding the data it operates, automatic properties must have get, set (the implementation cannot be given but the permission can be given), and it can be initialized

public string MySchool{get;set;}="smu";

rewrite

//使用这种重写操作后可以通过父类进行多态
public class food{
	public virtual void show()=>Console.WritenLine("food");
}
public class apple:food{
    public override void show()=>=>Console.WritenLine("apple");
}

//下面这种则是隐藏,通过子类当中的new关键字明确标目是隐藏
public class food{
	public void show()=>Console.WritenLine("food");
}
public class apple:food{
    new public void show()=>=>Console.WritenLine("apple");
}

The base keyword can be used to access the parent class members, and the this keyword can be used to access the current instance members, which are often used in limited field references or with the current instance as a parameter

Nesting of classes

Define the class in the class, you can set the permissions of the nested class according to your needs, and the nested class can access the private members of its outer class

interface

The encapsulation of methods and data is based on the principle of dependency inversion. The methods in the interface can only have abstraction and cannot be implemented , nor can they be instantiated

The difference between interface and class

  1. The default is public, and it can only be public
  2. Members cannot have a code body, and the permissions of its members can only be public (default), protected
  3. Members cannot be defined with virtual, sealed, abstract, static
  4. Type definition members cannot, but the new operator can be used to hide the method of its inherited interface

A class can implement multiple interfaces, an interface can be implemented by multiple classes, interfaces can also be used for polymorphism and inheritance, and interfaces can be contained in other classes .

Instructions

interface ICar:ITool{
    public void GetSize();
    public double GetSpeed();
    int Time{get;set;}//虽然接口中可以定义属性,但是这样的并不是自动实现的属性,因为接口中没有能够给他操作的类型定义变量,也就不能赋初值,可以只给出set/get,接口中的属性后面没有分号
}

The interface is defined without abstract and sealed

Common System Interface

//IDisposable接口
Dispose()//通过实现这个接口可以做到手动释放资源(注,可通过using关键字划定变量使用范围结束后自动dispose)

Implementation of the interface (take the previous ICar as an example)

A derived class also inherits the interface of its parent class, and the virtual keyword can be used when the parent class implements it, so that the subclass can override it. The interface implemented by the subclass, whose definition can appear in the parent class (but not only in the subclass, because the subclass can be regarded as the parent class, and vice versa)

public class Vehicle{
    public void GetSize(){}//实现方法可仅在父类中
}
public class Car:Vehicle,ICar
{
	public double GetSpeed(){} //这两种都是隐式实现,即可通过接口量也可通过对象去调用实现完了后的方法,还有显示实现,只能通过接口量去调用
	public int Time{get;set;}
}

inherit

C# inheritance is single inheritance (similar to java), all classes inherit from object (metaclass)

Inheritance

public class a:class_1,interface_1{} //需要注意接口必须在类名后面
public class a:b{
    a(int i,int j):base(i){}//其调用基类构造函数的方法类似于c++,基类名为base,不显示指明的话,就调用默认构造函数。在其后使用this关键字指明可以使调用构造函数前先调用其他的
}

Abstract class: A class that cannot be instantiated. The difference from an interface is that the methods in it can be implemented

public abstract class name{}
//抽象函数不能同时修饰virtual,同时抽象函数是不能有实现的

Derived classes cannot have higher access permissions than base classes

The sealed keyword can make the class cannot be inherited

polymorphism

A subclass can be transformed upwards into its parent class or its interface. When the subclass rewrites or implements the corresponding method, when calling the corresponding method in its parent class or interface, it actually calls the method of its subclass.

Rewriting: subclasses reimplement parent class methods, but this may override parent class methods

relationship between objects

containment (dependency)

The object under the dependency relationship will not automatically call the constructor of the contained object when it is instantiated, and it must be actively declared.

Collection relationship (array of objects)

event

Often used in wpf, a component (object) triggers its bound event function under a certain trigger condition (similar to qt signal and slot mechanism)

Use of dynamic link libraries

Partial classes and partial methods

The partial keyword enables classes to be defined in different files, often used to define some methods first, and give the implementation in another partial class

public partial class MyClass{
    partial void do_it();//部分类不能用static,以及其他涉及oop的修饰符,不能out参数,他们必须是私有的,并且不能有返回值
    public void make_it(){do_it();}//如果do_it未实现,那么编译器会忽视这个函数
}
public partial class MyClass{
    partial void do_it(){}
}

Some classes and some methods can be called in different .cs files

dynamic link library call

Create a dll file by ctrl+b

Import the dynamic library file that has been introduced into the project by using

gather

Collection classes are based on namespaces

System.Collections

Several of the core interfaces

ICollection

From IL

IDictionarty

IEnumerable

Collection

Define your own collection of custom types by inheriting the CollectionBase abstract class (this class implements the above four interfaces)

public class Animals:CollectionBase{
	public void Add(Animal new_animal)
    {
        List.Add(new_animal);
    }
    public Animal this[int index] //索引器,可以通过index直接得到对应索引中的数据(属性)
    {
        set{List[index]=value;}
        get{return (Animal)List[index];}
    }
    //定义完索引器后可以直接在后面的代码中通过this去使用List对应索引的值
}

Commonly used collection classes

ArrayList is similar to the vector of c++, and all the elements in it are stored as object objects, so when using it, it needs to be cast before calling the method of the corresponding type

ArrayList array=new ArrayList();
array.Add()
AddRange()
RemoveAt()
InsertRange()
.Count

Dictionary

C# has two key-value pair storage structures

  1. HashTable, in which all the contents are also stored as objects, when using foreach to traverse the hash table, the entry should use the DictionaryEntry type to access the corresponding value through Key, Value (the Value here must be converted first after returning) (similar to the pair in C++) ), the order of foreach traversing the dictionary is in reverse order , and the elements cannot be sorted directly, but can only be taken out in the sorted order, which is recommended in multi-threading . The key of this container is not unique
  2. Dictionary<type,type>, supports generics, and performs a foreach loop through KeyValuePair. When the dictionary is inserted, the data will be sorted sequentially, but the hash table will not, which is suitable for single-threaded use. The key for this container is unique. Through Key, Value to traverse to the corresponding attribute

common methods/properties common to both

Count
Add()//哈希表与字典的参数不同
Clear()
Keys()
Values()//这两个均返回集合
ContainsKey()
ContainsValue()

Provides a basic abstract class DictionaryBase similar to Collection, which can implement Add(), Remove and indexer by yourself like CollectionBase (eg. public string this[string index]{get...set...})

public class People:DictionaryBase{
    public void Add(string name,Person person)
    {
        InnerHashtable.Add(name,person);
    }
    public Person this[string key]{
        set{ InnerHashtable[key]=value;}
        get{ return InnerHashtable[key];}
    }
}

foreach

foreach execution process

Get the IEnumerator interface and call the MoveNext method. If it is true, then return the current reference, and call MoveNext again until it is false (equivalent to having a head pointer)

iterator

yield return value

Can iterate to return blocks of code (such as values ​​in methods)

The return type is

  1. IEnumerator (when iterating over classes)

  2. IEnumerable (when iterating over methods)

    In fact, all objects are returned

Use yield expressions to return values ​​multiple times in a code block

public static IEnumerable SimpleList()
{
    yield return 1;
    yield return 2;
    ...
}
foreach(int i in SimpleList)
{...}
//可以通过foreach去访问迭代器
class Primes{
    ...
    public IEnumerator GetEnumerator(){//如果想迭代类必须是这个函数名称
        yield return ...
    }  
}
//可以用过foreach去迭代这个类得到迭代器不断通过yield返回的值

Iterators are often used when a module generates multiple data, or to simplify the iterative operation of a custom dictionary (inherited from DictionaryBase), and the yield return of the iterator does not need to appear at the end of the corresponding code block

Both IEnumerator and IEnumerable are interfaces, but there is only one function returning IEnumerator in the latter, while the former defines functions such as MoveNext for processing traversal. often use the latter

Let's talk about copying

If the class contains only value types, shallow copying can be used directly for class objects. If the class contains a reference type, it means that only the reference of the reference type attribute will be copied during shallow copying, and deep copying must be used.

Create a new object of its own class to return by implementing the object Clone() method in ICloneable to achieve deep copying

class People:DictionaryBase,ICloneable
{
	...
	public object Clone()
	{
		People newp=new People();
		foreach(DictionaryEntry en in InnerHashTable )
			newp.Add((string)en.Key,new Person((Person)en.Value));
			//一定要创建新对象才能避免浅复制的问题
		return newp;
	}
}
...
//由于Clone函数返回的是object对象,所以在使用时还需要强制转换
People tp_people=(People)people.Clone();

Shallow copy can be achieved by directly calling MemberwiseClone()

Compare

type comparison

Use typeof with GetType (eg. obj.GetType()==typeof(class))

Sealing and unpacking

Box sealing: Encapsulate the value type into an object type

Unboxing: Unboxing the object type into a value type

(Copying a value type by boxing copies a reference to a copy of the value type, not a direct reference to the value type )

Comparison of several comparison methods: == CompareTo Equal

== compares references not content

Equal is comparing contents not references

str1.CompareTo(str2) is specially for string comparison and returns 0, then the content is equal to less than 0, then str1<str2

is operator

is

Used to compare whether an object is of a given type or a derived type of a given type or implements a given interface

void check(object obj)
{
	if(obj is classa) //这里obj可以自行转换成其他类
        ...
}

operator overloading

IComparable and IComparer interfaces

The former is an object for comparison, and the latter is a comparator for comparing two objects

class num:IComparable
{
	public int val;
	public int CompareTo(object obj)//可以接受任意类型的参数,需要注意给出类型处理
	{...}//只要返回负数,那么this的对象就放在obj对象的前面
	// public int Compare(object a,object b ){...} 实现IComparer
}

Under Collections, Comparer.Default is provided to implement the comparison function by default

This comparison class is often used to compare directly with the content (such as string) Comparer.Default.Compare() (type conversion is required first)

The above two interfaces are often used in custom sorting

collection sort

For ArrayList, Sort can be used to sort (ordinary arrays do not have this member function), for numeric types, the default is to sort in ascending order, and for strings, the default is to sort in dictionary order

Use sort for custom sorting, two methods

  1. Use the IComparable interface to implement the CompareTo function in the object class to be compared, and the CompareTo function returns a negative number, then this item is placed in front of the obj item , otherwise it is placed behind

    class Unit:IComparable{
        public int attack;
        public Unit(int v):attack(v){} 
        public int Comparable(object obj)
        {
            if(obj is Unit)
            {
                Unit tp=obj as Unit;
                if(attack>tp.attack)
                    return -1;
                else
                    return 1;
            }
            else
                throw new Exception();
        }
    }
    

    2. You can also implement a comparison class by implementing the interface IComparer, and directly pass this class to the Sort function, often through a singleton mode class.

    class Compare:IComparer{
        public static IComparer comparer=new Compare();
        private Compare(){}//单例模式下含有一个静态成员,构造函数为私有
        public int Compare(object a,object b)
        {//注意需要进行类型判断
            if(...)
                return -1;
            else
                return 1;
        }
    }
    List<int> list=new List<int>();
    list.Sort(Compare.comparer);
    //泛型实现方法
    class Comparer:IComparer<Type>
    {
    	...
    	public int Compare(Type t1,Type t2)
    	{
    	
    	}
    }
    

dictionary sort

Dictionary sorting can only convert all the data in the dictionary into ArrayList and then return it to the original dictionary after sorting according to Sort

convert

overloaded conversion operator

The as operator typea as typeb means that a can be converted to type b, but there are certain conditions

  1. typea is the type of typeb
  2. typea can be implicitly converted to typeb
  3. typea can be boxed into typeb
  4. typeb must be a reference type or a nullable type

Invalid conversion For example, when some parent classes are forced to convert to subclasses, Null will be returned

Exception checking can be done by checking for null

generic

nullable type

Nullable value types: Can Nullable t be shortened to T? t ( can be assigned as null ), there is a calculated value attribute as Value, and the operation between T? is similar to T (the general value type cannot be assigned to Null)

Operators for nullable types are often used to test for null

a ?? b 返回非空的那个对象的值
?.在对象调用方法返回数值时如果为空那么就返回null,往往和??联用
obj?.count()??SIZE

Nullable type, if it contains null operation, then return null

generic container

namespace is required

System.Collections.Generic

常用容器
List<T> t=new List<T>;
Dictionary<t k,t v> dict;

List sorting

List<T> t=new List<T>;
t.Sort()//默认排序;可以接受一个参数名为int fun(T x,T y);作为判断函数
//因为Sort有一个重载类型,其中参数为委托int Comparison<T,T>(T x,T y);

Or it can be similar to a non-generic method, let T implement the int CompareTo(T x) in the IComparable interface

generic class

class classname<T1,T2…>

If the specific type of T1 is not determined, it can only be read-only by default.

generic class keyword

default //可以根据类型把默认值赋值给变量(0/null)
where //对泛型类作约束
class name<t> c where t:C1,C2,C3 表示继承自c,约束限制为C1,C2,C3如果有多个T那么可以使用多个where来限制(where要在继承和实现后面)
class name<t1,t2> where t1:c1,c2 where t2:c3,c4{}
泛型类的构造函数签名依然是name(){}

generic inheritance

For a subclass, its generic type constraints cannot exceed the generic constraints of the parent class

Generic interface: interface Interface_name whose rules are consistent with generic inheritance

generic method

Return type function (parameter list) T here can be used for return type and parameter type. You can also use constraints to constrain the parameter types of generic methods

If you use a generic method in a generic class, you need to pay attention to the fact that the generic parameter letters of the method need to be different from the generic parameters of the class

For generic programming, when the type is unknown, it can only be regarded as a subclass of object, and only the four methods of object (GetType, ToString) can be used, so a step of type judgment is required in advance

generic delegate

delegate T function (corresponding parameter list) which can also be followed by constraints after delegation

Variants

The function is to use the interface generic type parameter as a variant parameter to deal with the inheritance of generic interface generic parameters, so that they can be assigned to each other

Covariant:

super implements interface, base implements interface

class super:base{}
interface<base> b;
interface<super> s=new super();
b=s;//通过协变使得如此的接口赋值能够成立

To enable the quantity of the subclass parameter generic interface to be assigned to the quantity of the parent class parameter generic interface, define the method:

The interface covariant parameter can only be used as the return value of the interface method or the get accessor of the property

Resistance to change:

Deals with a similar problem to covariance, with the difference that

interface variable parameters can only be used as parameter list types

exception handling

try {which contains the code where the exception occurred}

catch (contains the corresponding exception type) when (exception filter, a judgment condition) {handle exception}

finally {code block that will be executed eventually}

After an exception occurs, the following statements will not be executed until the first catch position that can be processed is encountered

Throw an exception (common practice)

throw new Exception(string? str/Exception exp)

C# Advanced Techniques

Var keyword

The Var type variable can be identified by the value you assign to it. It must be initialized, must be a local quantity, and cannot modify the type. You can also declare a var array, but the array must be of the same type.

Reflection and Properties

A characteristic means that the compiler can know some information about the class and give measures at compile time. Through the reflection mechanism, the type information can be dynamically checked at runtime, thereby obtaining the characteristic information. Attributes themselves can be used as decorators for classes

When using the method [property name ()], parameters can be selected, and the property can be customized

[AttributeUsage(AttributeTargets.Class|ttributeTargets.Method,AllowMultiple=false)]

Indicates that the target is a class and method, and does not allow multiple application features, and then follow a class with a custom constructor

[AttributeUsage(AttributeTargets.Class|ttributeTargets.Method,AllowMultiple=false)
public class Range{
    public int min{set;get;}
    public int max{set;get;}
}
//使用方法如下
 [Range(min=10,max=30)]
 public class People(){}
//通过转换成Type方法得到对应的特性信息
Type classType=typeof(People) 
object[] Attributes=classType.GetCustomAttrbutes(true);//得到自定义特性

Concurrency related

lock(instance){ … }

Locking is required for instances involving synchronization issues

Multithreading

The five life cycles of the thread are not started, ready, suspended, running, dead

System.Threading namespace

Thread class

Basic usage

Thread thread=new Thread(function);
thread.Start();//启动线程

Passing multiple parameters to the thread and returning a certain value in the thread requires a thread auxiliary class to implement

class ThreadFz{
	public int info;
	public string id;
	public ThreadFz(int f,string i)
	{
		info=f;
		id=i;
	}
    //用于处理线程执行的函数
	public void ThreadPro()
    {
        //do something
    }
}

//在线程中返回值,利用委托,在线程辅助类的构造函数中传递一个用于返回/打印特定值的函数
public delegate void getValue(int t);
//在类中
public getValue getval;
public ThreadFz(getValue getv)
{
    getval=getv;
}
//在主线程中
ThreadFZ fz=new ThreadFz(delegate(int t){
    Console.WriteLine(t);
})
//调用这个类对象的进程执行函数
Thread thread=new Thread(fz.ThreadPro());

Since threads are independent of each other, data cannot be directly transferred between threads. The ideas are as follows:

Set up a global hash table, the process number is the key, and the corresponding data structure is value (this value is a reference type), so that when the main process modifies the elements in the hash table, it is equivalent to modifying the elements in the thread. (Because the modification is a reference)

Thread Pool

Due to the high memory overhead of threads, the use of thread pools can limit the number of parallel threads to control memory overhead. The threads in the thread pool will not be destroyed after execution, but will be suspended in the thread pool. If the program applies for threads again, the suspended threads will be activated from the thread pool instead of creating new threads, thus reducing a lot of memory overhead .

When the thread reaches the maximum number of threads, the thread can be handed over to the system management, so as to concentrate on other tasks.

Handle the process pool through the static class ThreadPool

ThreadPool.SetMaxThreads(n,m); //设置最大工作数量
ThreadPool.QueueUserWorkItem(function,pars)//再直接把函数和参数放入池中即可(每加入依次会从线程池中尝试使用一个线程)
    
for(int i=0;i<n;i++)
    ThreadPool.QueueUserWorkItem(function(),pars)//跑n个线程

ThreadPool

multi-Progress

Process

Process p=new Process();
p.StartInfo.FileName = @"D:\Python2\python.exe"; //执行的文件绝对路径,注意这里要给出的是.exe文件
p.StartInfo.Arguments = sArguments;//执行文件的参数
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.Start();//启动进程

C# calls Python script

Specify the Python script, name, command line parameters, python.exe route, and call the Python script through multiple processes. This method can be used to execute Python files

using System;
using System.Collections;
using System.Diagnostics;

namespace Test
{
  class Program
  {
    static void Main(string[] args)
    {
      Process p = new Process();
      string path = "reset_ipc.py";//待处理python文件的路径,本例中放在debug文件夹下
      string sArguments = path;
      ArrayList arrayList = new ArrayList();
      arrayList.Add("com4");
      arrayList.Add(57600);
      arrayList.Add("password");
      foreach (var param in arrayList)//添加参数
      {
        sArguments += " " + sigstr;
      }

      //这段代码的意思相当于表示给定命令参数情况下,运行绝对路径指明的进程。
      p.StartInfo.FileName = @"D:\Python2\python.exe"; //python2.7的安装路径
      p.StartInfo.Arguments = sArguments;//python命令的参数
      p.StartInfo.UseShellExecute = false;
      p.StartInfo.RedirectStandardOutput = true;
      p.StartInfo.RedirectStandardInput = true;
      p.StartInfo.RedirectStandardError = true;
      p.StartInfo.CreateNoWindow = true;
      p.Start();//启动进程

      Console.WriteLine("执行完毕!");

      Console.ReadKey();
    }
  }
}

C# commonly used IO content

All need IO package

File

This type provides static functions for reading and writing files

Exists
Create
Open
ReadAllText
ReadAllLines
ReadAllBytes
WriteAllText
WriteAllLines
WriteAllBytes
AppendAllLines
AppendAllText

Directory

This type provides static functions for reading and writing directories

Exists
Delete
CreateDirectory
GetDirectories

MemoryStream

Used to read and write memory, often used as middleware for stream reading and writing (equivalent to using memory as a buffer for reading and writing, because it is fast?), common methods and examples are as follows:

MemoryStream ms=new MemoryStream(int size);//声明一块可扩展大小的用来读写的内存区域
ms.Write(str,0,str.Lenght);//将str(byte数组)中,从0开始长度为Length的数据内容写入内存
ms.Seek(offset,loc);//可以设定目前内存流要读写的位置,loc是可以是起点,终点或者当前位置,offset是loc的偏移量
ms.Read(buffer,0,size);//ms当前流中长度为size的内容会写入到buffer中0到size-1的位置
ms.ToArray();//目前ms中的内容会全部被返回成一个字节数组;

BinaryReader

Used to read binary objects, by passing FileStream (file stream object) to read. Commonly used functions and examples are as follows:

//二进制文件读写处理
BinaryReader reader=new BinaryReader();
reader.Read(byte[] buffer,int start,int count);
ReadBoolean()
ReadByte(int)
ReadChar()
ReadDouble()
ReadString()
...
//例子,利用MemoryStream作读写文件的中间状态来读写
//相当于把文件中的所有内容读入内存当中后,再返回一个大的bytes数组,从而得到文件中的内容
//之所以要经过MemoryStream是因为内存读写速度足够快,并且可以节省一些中间临时文件的开销
const int bufferSize = 4096;
using (var ms = new MemoryStream())
{
    byte[] buffer = new byte[bufferSize];
    int count;
    while ((count = reader.Read(buffer, 0, buffer.Length)) != 0)
        ms.Write(buffer, 0, count);
    return ms.ToArray();
}

BitConverter

StreamReader

Through a specific encoding method, char information is read from the byte stream, which is often used in network communication (such as streaming TCP connections)

Common methods and examples are as follows:

StreamReader reader=new StreamReader(Stream,Encoding);//构造函数为目标流以及编码方式(可选)
ReadLine();//从当前流中读取数据并且返回一行内容

StreamWriter

# C# common mathematical processing

C# time processing

## DateTime

For ultra-high-precision timing, you can use DateTime.Now.Ticks that comes with .net. 1 ticks is equal to 100 nanoseconds, which is equivalent to 10^4 ticks is equal to 1 millisecond, so 5000 ticks is equivalent to 0.5 milliseconds, you can use ticks The difference is used for ultra-high-precision timing. The details are as follows:

while (DateTime.Now.Ticks - current <= 6000) ;
current = DateTime.Now.Ticks;

Timer

The timer module commonly used in C#, the highest progress can reach milliseconds, and the smaller precision can be realized through DateTime.Now.Ticks or system calls. The specific usage method is as follows:

Timer timer = new Timer();
timer.Elapsed += delegate (Object source, ElapsedEventArgs e) { Console.WriteLine("Signal"); };
timer.Interval = 2000;
timer.Enabled = true;
timer.AutoReset = true;
timer.Start();
Console.WriteLine("Start_Timer");
while (true) {; }

DateTime.Now.Ticks is often used for the response time between hardware and hardware that requires ultra-high precision. General user-level programs often use TImer directly.

Guess you like

Origin blog.csdn.net/qq_38069320/article/details/106390602