当前位置:网站首页>C common function integration
C common function integration
2022-07-26 14:37:00 【Xiongsiyu】
Catalog
String conversion DateTime type
Net5 Add administrator rights Run as administrator
Task Perform tasks , Waiting for the task to complete
Realize the simulation of keyboard keys
Get and set the specified properties through reflection
Threads
Before using multithreading technology , First, we need to understand what thread is .
So what is thread ? When it comes to threads, we have to talk about processes first . In layman's terms , A process is an application that starts running , Then there will be a process belonging to this application .
Then the thread is the basic execution unit in the process , There is at least one thread in each process , This thread is created according to the process creation , So we call this thread the main thread .
So many threads include other threads besides the main thread .
If a thread can perform a task , So multithreading can execute multiple tasks at the same time .
Basic usage of threads :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Threads
{
public partial class Form1 : Form
{
private List<Thread> ThreadPool = new List<Thread>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Thread thread = new Thread(TestThread);
ThreadPool.Add(thread);
thread.Start();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if(ThreadPool.Count > 0)
{
foreach (Thread thread in ThreadPool)
{
if (thread.IsAlive)// Whether the current thread terminates
{
thread.Abort();// Thread termination
}
}
}
}
private void TestThread()
{
for (int i = 0; i <= 10; i++)
{
Console.WriteLine(" Output :" + i);
Thread.Sleep(500);
}
}
private void Button_Test_Click(object sender, EventArgs e)
{
if (ThreadPool.Count > 0)
{
foreach (Thread thread in ThreadPool)
{
Console.WriteLine(" Whether the current thread terminates :" + thread.IsAlive);
}
}
}
}
}
MD5 encryption
/// <summary>
/// Calculation md5
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private string CalcMD5(string str)
{
byte[] buffer = Encoding.UTF8.GetBytes(str);
using (MD5 md5 = MD5.Create())
{
byte[] md5Bytes = md5.ComputeHash(buffer);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < md5Bytes.Length; i++)
{
sb.Append(md5Bytes[i].ToString("x2"));//X2 when , Generate capital letters MD5
}
return sb.ToString();
}
}
Calculate two time intervals
Code
/// <summary>
/// Calculate the duration of the two time intervals
/// </summary>
/// <param name="TimeType"> Time type returned </param>
/// <param name="StartTime"> Starting time </param>
/// <param name="EndTime"> End time </param>
/// <returns> Return interval , The time type of the interval depends on the parameter TimeType distinguish </returns>
public static int GetSpanTime(TimeType TimeType, DateTime StartTime, DateTime EndTime)
{
TimeSpan ts1 = new TimeSpan(StartTime.Ticks);
TimeSpan ts2 = new TimeSpan(EndTime.Ticks);
TimeSpan ts = ts1.Subtract(ts2).Duration();
//TimeSpan ts = EndTime - StartTime;
double result = 0;
switch (TimeType)
{
case TimeType.Seconds:
result = ts.TotalSeconds;
break;
case TimeType.Minutes:
result = ts.TotalMinutes;
break;
case TimeType.Hours:
result = ts.TotalHours;
break;
case TimeType.Days:
result = ts.TotalDays;
break;
}
return Convert.ToInt32(result);
}
/// <summary>
/// Time type
/// </summary>
public enum TimeType
{
/// <summary>
/// second
/// </summary>
Seconds = 0,
/// <summary>
/// minute
/// </summary>
Minutes = 1,
/// <summary>
/// Hours
/// </summary>
Hours = 2,
/// <summary>
/// God
/// </summary>
Days = 3,
/// <summary>
/// month
/// </summary>
Months = 4
}call :
class Program
{
static void Main(string[] args)
{
DateTime dateTime1 = DateTime.Now;
Thread.Sleep(3000);
DateTime dateTime2 = DateTime.Now;
int result = GetSpanTime(TimeType.Seconds, dateTime1, dateTime2);
Console.WriteLine(string.Format("{0} {1}", result, TimeType.Seconds.ToString()));
Console.ReadKey();
}
}Output :
3 Seconds
Array equal scale
Create a new one C# Console project , To create a new .NetFramework Type of , Otherwise, some of the following code API Can't use .
Code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test1
{
class Program
{
static void Main(string[] args)
{
List<double> resultList = ScaleConversion(new List<double>() { 230, 2453, 4353, 65 }, 10);
string value = string.Empty;
for (int i = 0; i < resultList.Count; i++)
{
value += string.Format("{0},", resultList[i]);
}
Console.WriteLine(value);
Console.ReadKey();
}
/// <summary>
/// Scale the array equally
/// </summary>
/// <param name="valueList"> Array </param>
/// <param name="maxScale"> Maximum zoom , The minimum value is... By default 0</param>
/// <returns> Scaled array </returns>
public static List<double> ScaleConversion(List<double> valueList, int maxScale)
{
if (valueList == null || valueList.Count == 0)
{
Console.WriteLine("valueList Can't be empty ");
return null;
}
if (maxScale < 10)
{
Console.WriteLine(" The maximum value of equal proportion cannot be less than 10");
return null;
}
double max = valueList.Max();
double factor = Math.Round(max / maxScale, 2);// coefficient
List<double> result = new List<double>();
for (int i = 0; i < valueList.Count; i++)
{
result.Add(Math.Round(valueList[i] / factor, 2));
}
if (result.Count > 0)
return result;
return null;
}
}
}After operation , The result is :0.53,5.64,10,0.15,
Here is the general 10 As the maximum value in the scale , Interested readers can calculate whether it is correct .
Time plus minus
Code :
using System;
namespace Util
{
public class TimeCompute
{
/// <summary>
/// The time interval
/// </summary>
/// <param name="DateTime1"> Time 1</param>
/// <param name="DateTime2"> Time 2</param>
/// <returns> The integral part of the minutes separated on the same day </returns>
public static int DateDiff(DateTime DateTime1, DateTime DateTime2)
{
TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
TimeSpan ts = ts1.Subtract(ts2).Duration();
return Convert.ToInt32(ts.TotalMinutes);
}
/// <summary>
/// Time adds up
/// </summary>
/// <param name="DateTime1"> Time 1</param>
/// <param name="DateTime2"> Time 2</param>
/// <returns> Time and </returns>
public static DateTime DateSum(DateTime DateTime1, DateTime DateTime2)
{
DateTime1 = DateTime1.AddHours(DateTime2.Hour);
DateTime1 = DateTime1.AddMinutes(DateTime2.Minute);
DateTime1 = DateTime1.AddSeconds(DateTime2.Second);
return DateTime1;
}
/// <summary>
/// According to the number of seconds DateTime
/// </summary>
/// <param name="seconds"> Number of seconds </param>
/// <returns> With 1970-01-01 Is the time of the date </returns>
public static DateTime GetDateTimeBySeconds(double seconds)
{
return DateTime.Parse(DateTime.Now.ToString("1970-01-01 00:00:00")).AddSeconds(seconds);
}
/// <summary>
/// according to DateTime Get the number of seconds
/// </summary>
/// <param name="timer"> Time </param>
/// <returns> Number of seconds </returns>
public static double GetDateTimeBySeconds(DateTime dateTime)
{
return (Convert.ToInt32(dateTime.Hour) * 3600) + (Convert.ToInt32(dateTime.Minute) * 60) + Convert.ToInt32(dateTime.Second);
}
}
}Convert string to time
It can also be used here DateTime.Parse convert , If the time string is not well written , Only time , No date , It will be combined with the current date and the time in the string
DateTime dt = Convert.ToDateTime("1:00:00");Subtract two times
DateTime t1 = DateTime.Parse("2007-01-01");
DateTime t2 = DateTime.Parse("2006-01-01");
TimeSpan t3 = t1 - t2;String conversion DateTime type
Code
// The following two string writing methods are OK
string timer = "2022-02-02 18:15:58";
string timer = "2022/2/18 18:18:26";
DateTime dateTime = Convert.ToDateTime(timer);
Console.WriteLine(dateTime);
Net5 Add administrator rights Run as administrator
stay project On Add a new item choice “ Application manifest file ” And then click add to Button

After adding , The default app.manifest file , take :
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
It is amended as follows :
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />


Rebuild the project , You will be prompted when you open the program again Need to run with administrator privileges .
Task Perform tasks , Waiting for the task to complete
Code :
// Mission
Func<int> Funcs = () =>
{
Console.WriteLine(" The task begins ");
return 1 + 1;
};
// Perform tasks
Task<int> printRes = Task.Run(Funcs);
// Waiting for the task to complete
printRes.GetAwaiter().OnCompleted(() =>
{
Console.WriteLine(" Asynchronous execution result :" + printRes.Result);
});
function :
The task begins
Asynchronous execution result :2
use “\” Split characters
string Chars = @"\";
string Text = @"ddsdd\dddds";
string[] Arr = Text.Split(new[] { Chars },StringSplitOptions.None);
// result :Arr[0] = "ddsdd, Arr[1] = dddds
Realize the simulation of keyboard keys
1. Send string , The string here can be any character
private void button1_Click(object sender,EventArgs e)
{
textBox1.Focus();
SendKeys.Send("{A}");
}2. Analog key combination :CTRL + A
private void button1_Click(object sender,EventArgs e)
{
webBrowser1.Focus();
SendKeys.Send("^{A}");
}3.SendKeys.Send Asynchronous analog key ( Don't block UI)
Key reference : virtual key code (Winuser.h) - Win32 apps | Microsoft Docs
[DllImport("user32.dll", EntryPoint = "keybd_event", SetLastError = true)]
//bvk Virtual key value of the key , If the Enter key is vk_return, tab The key is vk_tab( See Appendix for other details )
//bScan Scan code , In general, there is no need to set , use 0 Just replace it ;
//dwFlags Option logo , If keydown Then put 0 that will do , If keyup Set it to "KEYEVENTF_KEYUP";
//dwExtraInfo Generally, it is also set 0 that will do .
public static extern void keybd_event(Keys bVk, byte bScan, uint dwFlags, uint dwExtraInfo);
private void button1_Click(object sender,EventArgs e)
{
textBox1.Focus();
keybd_event(Keys.A, 0, 0, 0);
}4. Analog key combination :CTRL + A
public const int KEYEVENTF_KEYUP = 2;
private void button1_Click(object sender,EventArgs e)
{
webBrowser1.Focus();
keybd_event(Keys.ControlKey,0,0,0);
keybd_event(Keys.A,0,0,0);
keybd_event(Keys.ControlKey,KEYEVENTF_KEYUP,0,0);
}5. The above two methods are global , Now let's introduce how to simulate the key pressing of a single window
The following code has not been tested , I don't know if it works
[DllImport("user32.dll",EntryPoint = "PostMessageA",SetLastError = true)]
public static extern int PostMessage(IntPtr hWnd,int Msg,Keys wParam,int lParam);
public const int WM_CHAR = 256;
private void button1_Click(object sender,EventArgs e)
{
textBox1.Focus();
PostMessage(textBox1.Handle,256,Keys.A,2);
}public const int WM_KEYDOWN = 256;
public const int WM_KEYUP = 257;
private void button1_Click(object sender,0)
{
PostMessage(webBrowser1.Handle,WM_KEYDOWN,0);
}The code takes time to run
This function is relatively simple in code implementation , A few lines of code can do
Declaration timer
System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();Pause timer , Output time
stopwatch.Stop();
Console.WriteLine(stopwatch.Elapsed.Minutes + " branch " + stopwatch.Elapsed.Seconds + " second ");If you need to time multiple times in segments , Then you need to clear the timer
stopwatch.Stop();
stopwatch.Reset();
stopwatch.Start();Get and set the specified properties through reflection
public class Program
{
// Defining classes
public class MyClass
{
public int Property1 { get; set; }
}
static void Main()
{
MyClass tmp_Class = new MyClass();
tmp_Class.Property1 = 2;
// Access to type
Type type = tmp_Class.GetType();
// Gets the property with the specified name
System.Reflection.PropertyInfo propertyInfo = type.GetProperty("Property1");
// Get attribute value
int value_Old = (int)propertyInfo.GetValue(tmp_Class, null);
Console.WriteLine(value_Old);
// Assign a value to
propertyInfo.SetValue(tmp_Class, 5, null);
int value_New = (int)propertyInfo.GetValue(tmp_Class, null);
Console.WriteLine(value_New);
Console.ReadLine();
}
}Feature play 1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace characteristic
{
public class Program
{
static void Main(string[] args)
{
// Get all classes of the assembly
Type[] types = typeof(Program).Assembly.GetTypes();
// Traverse all classes
foreach (Type t in types)
{
// Traverse all methods of the current class
foreach (MethodInfo method in t.GetMethods())
{
// Traverse all features on the current method
foreach (Attribute attr in method.GetCustomAttributes())
{
// If the feature is GameSystem
if (attr is GameSystem)
{
// Instantiate an instance of the current class
object reflectTest = Activator.CreateInstance(t);
// Get the name of the current method
MethodInfo methodInfo = t.GetMethod(method.Name);
// Execute the current method
methodInfo.Invoke(reflectTest, null);
}
}
}
}
Console.ReadKey();
}
}
// Custom attribute class
[AttributeUsage(AttributeTargets.All)]
public class GameSystem : Attribute// The normal format is GameSystemAttribute In this way
{
public GameSystem() { }
}
// Customize a player class
public class player
{
//GameSystem The name of the feature class , If the name of the feature class is like this when defining GameSystemAttribute The same is true with features
[GameSystem]
public void Start()
{
Console.WriteLine("GameSystem start");
}
[GameSystem]
public void Updata()
{
Console.WriteLine("GameSystem updata");
}
public void Awaken()
{
Console.WriteLine("Awaken~~~~~~");
}
}
}
function :

Generic gameplay 2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Test_Console
{
class Program
{
static void Main(string[] args)
{
Test test = new Test();
test.Print<Dog>().Run();
test.Print<Cat>().Run();
//test.Print<Chook>().ChickenFlew();// Report errors , Because it didn't come true Movement Interface
Console.ReadKey();
}
}
public class Test
{
private Dictionary<string, object> ObjectDictionary = new Dictionary<string, object>();
public T Print<T>() where T: class, Movement, new()
{
Type t = typeof(T);
string fullName = t.FullName;
if (ObjectDictionary.ContainsKey(fullName))
{
return (T)ObjectDictionary[fullName];
}
else
{
object obj = Activator.CreateInstance(t);
ObjectDictionary.Add(fullName, obj);
return (T)obj;
}
}
}
public interface Movement
{
void Run();
}
public class Dog : Movement
{
public void Run()
{
Console.WriteLine(" The dog ran away ");
}
}
public class Cat : Movement
{
public void Run()
{
Console.WriteLine(" The cat ran away ");
}
}
public class Chook
{
public void ChickenFlew()
{
Console.WriteLine(" The chicken flies ");
}
}
}
function :

Generic
The significance of generics is that it eliminates the overhead of converting between types , And overloading of similar methods ,
such as ,Add Method you need to overload two methods (int and double) Or more , Write only one in the form Add The method can be completed int,double,float...... And so on ,
Again , Operations on collections , No, it is often a weak type (object), And using a paradigm can directly be a strong type , No overhead between transformations , Saved resources ,
Code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _01_ Custom generics
{
class Program
{
static void Main(string[] args)
{
// Generic classes
MyClass1<string> myClass = new MyClass1<string>();
myClass.SayHi(" Xi xi xi ");
// Commissioned by the generic
MyGenericDelegate<string> md = m1;
md(" Commissioned by the generic ");
Console.ReadKey();
}
public static void m1(string msg)
{
Console.WriteLine(msg);
}
/// <summary>
/// Generic classes
/// </summary>
/// <typeparam name="T"></typeparam>
public class MyClass1<T>
{
public void SayHi(T arg)
{
Console.WriteLine(arg);
}
}
public class MyClass2
{
/// <summary>
/// Generic methods
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="msg"></param>
public void SayHi<T>(T msg)
{
Console.WriteLine(msg);
}
}
/// <summary>
/// Generic interface
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IFace<T>
{
void SayHi(T msg);
}
//----- There are two ways to implement generic interfaces -----
/// <summary>
/// 1. Common classes implement generic interfaces
/// </summary>
public class MyClass3 : IFace<string>
{
public void SayHi(string msg)
{
Console.WriteLine(msg);
}
}
/// <summary>
/// 2. Generic classes inherit generic interfaces
/// </summary>
/// <typeparam name="T"></typeparam>
public class MyClass4<T> : IFace<T>
{
public void SayHi(T msg)
{
Console.WriteLine(msg);
}
}
/// <summary>
/// Generic constraint
/// </summary>
public class MyClass5<T,K,V,W,X>
where T : struct // constraint T Must be of value type
where K : class // constraint K Must be a reference type
where V : IFace<T> // constraint V Must be realized IFace Interface
where W: K // W Must be K type , perhaps K Subclass of type
where X : class,new() // X Must be a reference type , And there is a parameterless constructor , When there are multiple constraints ,new() Must be written at the end
{
public void Add(T num)
{
Console.WriteLine(num);
}
}
/// <summary>
/// Commissioned by the generic
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="args"></param>
public delegate void MyGenericDelegate<T>(T args);
}
}end
边栏推荐
猜你喜欢

Iscc2021 lock problem solution

1-to-1 live broadcast source code - 1-to-1 voice chat source code

C语言入门必刷100题合集之每日一题(1-20)

在检测分割中一些轻量级网络模型(自己学习的笔记分享)

1对1直播源码——1对1语音聊天源码

10 schemes to ensure interface data security

嵌入式开发:调试嵌入式软件的技巧

Basic knowledge about memory chips

Comparison between agile development and Devops
![[Yugong series] July 2022 go teaching course 017 - if of branch structure](/img/e4/b3aa4b8bda738aadded3127a8b3485.png)
[Yugong series] July 2022 go teaching course 017 - if of branch structure
随机推荐
[Yugong series] July 2022 go teaching course 017 - if of branch structure
How to evaluate the test quality?
注解和反射
Jzoffer51- reverse pairs in the array (merge sort solution)
保证接口数据安全的10种方案
Leetcode36 effective Sudoku
【1.2.投资的收益和风险】
VP视频结构化框架
Disease knowledge discovery based on spo semantic triples
Learning basic knowledge of Android security
[integer programming]
Joint entity and event extraction model based on multi task deep learning
Redis的数据操作
~6. ccf 2021-09-1 数组推导
Research on Chinese medicine assisted diagnosis and treatment scheme integrating multiple natural language processing tasks -- taking diabetes as an example
[ostep] 04 virtualized CPU - process scheduling strategy
TDengine 助力西门子轻量级数字化解决方案 SIMICAS 简化数据处理流程
SP export map to Maya
14. Bridge based active domain adaptation for aspect term extraction reading notes
Uni app from creation to operation to wechat developer tool