C#入门基础

using System; using System.IO; using System.Net; using System.Text; using System.Reflection; using System.Collections; using System.Collections.Generic; using System.Text.RegularExpressions; namespace C_Notes { class Program { static void Main_String_Basix(string[] args) { //How to run C# in VS Code? /* step 0: create a null folder and open it in vscode step 1: dotnet new console step 2: dotnet restore step 3: dotnet run */ Console.WriteLine("Hello World!"); //////////////////////////////////// //Common string is unchangable string str = "hello//:www.world.edu.uk"; int result = str.CompareTo("hello");//return 0 when 2 strings are the same result = string.Compare(str, "hello");//same as above Console.WriteLine(result);//0 result = str.CompareTo("hallo");//return 1 when the first different letter-index in string is lager result = string.Compare(str, "hallo");//same as above Console.WriteLine(result);//1 result = str.CompareTo("hillo");//return -1 when the first different letter-index in string is smaller result = string.Compare(str, "hillo");//same as above Console.WriteLine(result);//-1 string newStr = str.Replace("ll", "ff");//replacement won't change original string Console.WriteLine($"Original:{str}. New:{newStr}.");//original string is still the originale one string targetString = "world"; int indexOfTargetString = str.IndexOf(targetString);//returns the index of the first letter in target string Console.WriteLine($"index of {targetString} is {indexOfTargetString}");//12 indexOfTargetString = str.IndexOf(targetString + "X");//return -1 if no target string was found Console.WriteLine($"index of {targetString + "X"} is {indexOfTargetString}");//-1 //Use them in comprohensive way such as below: if (!str.IndexOf(targetString).Equals(-1)) { string m_targetString = str.Substring(str.IndexOf(targetString), targetString.Length); Console.WriteLine($"my target string from the sentence: {m_targetString}"); } //////////////////////////////////// //Common string is unchangable and may cause wastes //We use string builder to create strings which often changes StringBuilder stringBuilder = new StringBuilder("Hello World!"); StringBuilder stringBuilder2 = new StringBuilder(100);//open string space size of 100, space will be extended if exceeds StringBuilder stringBuilder3 = new StringBuilder("Hello World!", 100);//initialize and open 100 soze of string space, space will be extended if exceeds Console.WriteLine(stringBuilder); stringBuilder.Append("---By Alexander");//Effective Console.WriteLine(stringBuilder); stringBuilder.Insert(5, "*a lamp inserted*"); Console.WriteLine(stringBuilder); stringBuilder.Replace("Hello", "Conia sayo");//This will affect the original string Console.WriteLine(stringBuilder);//original string has been changed stringBuilder.Clear(); Console.WriteLine(stringBuilder); } ////////////////////////////////////////////// static void Main_Regx_Basix(string[] args) { // if (IsInputMatchesNumber()) if (IsInputMatchesNumberByRegx()) { Console.WriteLine("Input charectors are all numbers."); } else { Console.WriteLine("Input charectors are not pure numbers."); } } //Common way to judge whether a string is pure numbers or not static bool IsInputMatchesNumber() { Console.Write("Please input your password: "); string str = Console.ReadLine(); bool isMatch = true; for (int i = 0; i < str.Length; i++) { if (str[i] < '0' || str[i] > '9') { isMatch = false; break; } } return isMatch; } //Use regular expressions to judge, result is the same as above static bool IsInputMatchesNumberByRegx() { Console.Write("Please input your password: "); string str = Console.ReadLine(); //Regular expression always come with @ // @ means "do not convert \ in string" // ^ means "start from" // $ means "end at" // * means "has any" // \d means "number" string pattern = @"^\d*$"; return Regex.IsMatch(str, pattern); } ////////////////////////////////////////////// static void Main_Delegate_Basix(string[] args) { int x = 100; int y = 300; //Get the pointer of the function "ToStirng" and apply it to the varible getAString GetAString getAString = new GetAString(x.ToString); GetAString getAString2 = x.ToString;//2nd Way to define: same as above Console.WriteLine(getAString());//Usable while calling by varible "getAString" Console.WriteLine(getAString2());//Usable while calling by varible "getAString2" string str = getAString.Invoke();//2nd way to call string str2 = getAString2.Invoke();//2nd way to call Console.WriteLine(str); Console.WriteLine(str2); MethodHolder myMethod = new MethodHolder(y.ToString); Console.WriteLine(AnotherMethod(myMethod)); } //Signature of the delegate delegate void VoidFuncWithOneParameter(int parameter); delegate int IntFuncWithOneParameter(int parameter); delegate int IntFuncWithTwoParameters(int parameterInt, string parameterStr); delegate string GetAString();//This will be treated as a class /*!IMPORTANT!*/ delegate string MethodHolder(); //delegate can be used to send a method as parameter to another method static string AnotherMethod(MethodHolder method) { return method();//just like a callback-function in JS } ////////////////////////////////////////////// static void Main_Action_Basix(string[] args) { //Action is a delegate which points to a void method without parameters Action voidMethod = Method; voidMethod(); //Action<type of parameter> can points to a void method with parameters Action<int> voidMethodWithParameters = MethodWithParameters; voidMethodWithParameters(5); } static void Method() { Console.WriteLine("This is a method which returns nothing."); } static void MethodWithParameters(int parameter) { if (parameter > 0) { for (int i = 0; i < parameter; i++) { Console.WriteLine("This is a void method with a parameter."); } } else { Console.WriteLine("Parameter should be greater than 0"); } } ////////////////////////////////////////////// static void Main_Func_Basix(string[] args) { //The last parameter in "Func" is the type of return-value the method //while the former parameters are all the parameters' type of the target method Func<string, int, bool, float> matureMethod = MatureMethod; matureMethod("Hello world!", 6, true); //The single parameter means the return-value of the method Func<bool> simpleMethod = SimpleMethod; Console.WriteLine(simpleMethod()); } static float MatureMethod(string parameterStr, int parameterInt, bool parameterBool) { if (parameterBool && parameterInt > 0) { for (int i = 0; i < parameterInt; i++) { Console.WriteLine($"{i} : {parameterStr}"); } return 0.618f; } else { Console.WriteLine("3rd parameter is set to false or the 2nd parameter is smaller than 0"); return 3.14f; } } static bool SimpleMethod() { return true; } ////////////////////////////////////////////// //Little utils ////////////////////////////////////////////// static void Main_TestUtils(string[] args) { Console.WriteLine(CheckPageUrl("www.baidu.com")); Console.WriteLine(CheckPageUrl("http://www.baidu.com")); Console.WriteLine(WriteLog.WriteMessage("hello!")); } /// <summary> /// 判断网址是否可以访问 /// </summary> /// <param name="Url"></param> /// <returns></returns> protected static bool CheckPageUrl(string url) { bool result = false; try { if (url.IndexOf("http").Equals(-1)) { url = "http://" + url; // Console.WriteLine(url); } HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url); myHttpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko"; myHttpWebRequest.Method = "GET"; HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); if (myHttpWebResponse.StatusCode == HttpStatusCode.OK) { result = true; } myHttpWebResponse.Close(); } catch { result = false; } return result; } } public class WriteLog { /// <summary> /// 将错误写入文件中 /// </summary> /// <param name="fileName">文件名</param> /// <param name="exception">发生的异常</param> public static void WriteErorrLog(string fileName, Exception exception) { if (exception == null) return; //ex = null 返回 DateTime dt = DateTime.Now; // 设置日志时间 string time = dt.ToString("yyyy-MM-dd HH:mm:ss"); //年-月-日 时:分:秒 string logName = dt.ToString("yyyy-MM-dd"); //日志名称 string logPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, Path.Combine("log", fileName)); //日志存放路径 string log = Path.Combine(logPath, string.Format("{0}.log", logName)); //路径 + 名称 try { FileInfo info = new FileInfo(log); if (info.Directory != null && !info.Directory.Exists) { info.Directory.Create(); } using (StreamWriter write = new StreamWriter(log, true, Encoding.GetEncoding("utf-8"))) { write.WriteLine(time); write.WriteLine(exception.Message); write.WriteLine("异常信息:" + exception); write.WriteLine("异常堆栈:" + exception.StackTrace); write.WriteLine("异常简述:" + exception.Message); write.WriteLine("\r\n----------------------------------\r\n"); write.Flush(); write.Close(); write.Dispose(); } } catch { } } /// <summary> /// 将终端内容打印到文件中 /// </summary> /// <param name="fileName">文件名</param> /// <param name="message">所要写入的内容</param> public static bool WriteMessage(string fileName, string message) { //ex = null 返回 DateTime dt = DateTime.Now; // 设置日志时间 string time = dt.ToString("yyyy-MM-dd HH:mm:ss"); //年-月-日 时:分:秒 string logName = dt.ToString("yyyy-MM-dd"); //日志名称 string logPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, Path.Combine("log", fileName)); //日志存放路径 string log = Path.Combine(logPath, string.Format("{0}.log", logName)); //路径 + 名称 try { FileInfo info = new FileInfo(log); if (info.Directory != null && !info.Directory.Exists) { info.Directory.Create(); } using (StreamWriter write = new StreamWriter(log, true, Encoding.GetEncoding("utf-8"))) { write.WriteLine(time); write.WriteLine("信息:" + message); write.WriteLine("\r\n----------------------------------\r\n"); write.Flush(); write.Close(); write.Dispose(); } return true; } catch (Exception e) { WriteErorrLog("WriteMessageException", e); return false; } } /// <summary> /// 将错误写入文件中 /// </summary> /// <param name="exception">发生的错误</param> /// <param name="message">需要写入的消息</param> public static bool WriteErorrLog(Exception exception, string message) { if (exception == null) return false; //ex = null 返回 DateTime dt = DateTime.Now; // 设置日志时间 string time = dt.ToString("yyyy-MM-dd HH:mm:ss"); //年-月-日 时:分:秒 string logName = dt.ToString("yyyy-MM-dd"); //日志名称 string logPath = System.AppDomain.CurrentDomain.BaseDirectory; //日志存放路径 string log = Path.Combine(Path.Combine(logPath, "log"), string.Format("{0}.log", logName)); //路径 + 名称 try { FileInfo info = new FileInfo(log); if (info.Directory != null && !info.Directory.Exists) { info.Directory.Create(); } using (StreamWriter write = new StreamWriter(log, true, Encoding.GetEncoding("utf-8"))) { write.WriteLine(time); write.WriteLine(exception.Message); write.WriteLine("异常信息:" + exception); write.WriteLine("异常堆栈:" + exception.StackTrace); write.WriteLine("异常简述:" + message); write.WriteLine("\r\n----------------------------------\r\n"); write.Flush(); write.Close(); write.Dispose(); } return true; } catch (Exception e) { WriteMessage("ErrorLogException", e.ToString()); return false; } } /// <summary> /// 将消息写入文件 /// </summary> /// <param name="message">需要写入的内容</param> public static bool WriteMessage(string message) { //ex = null 返回 DateTime dt = DateTime.Now; // 设置日志时间 string time = dt.ToString("yyyy-MM-dd HH:mm:ss"); //年-月-日 时:分:秒 string logName = dt.ToString("yyyy-MM-dd"); //日志名称 string logPath = System.AppDomain.CurrentDomain.BaseDirectory; //日志存放路径 // System.Console.WriteLine(logPath); string log = Path.Combine(Path.Combine(logPath, "log"), string.Format("{0}.log", logName)); //路径 + 名称 try { FileInfo info = new FileInfo(log); if (info.Directory != null && !info.Directory.Exists) { info.Directory.Create(); } using (StreamWriter write = new StreamWriter(log, true, Encoding.GetEncoding("utf-8"))) { write.WriteLine(time); write.WriteLine("信息:" + message); write.WriteLine("\r\n----------------------------------\r\n"); write.Flush(); write.Close(); write.Dispose(); } return true; } catch (Exception e) { WriteErorrLog("WriteMessageException", e); return false; } } } }

__EOF__

本文作者艾孜尔江
本文链接https://www.cnblogs.com/ezhar/p/12865848.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   艾孜尔江  阅读(155)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示