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;
            }
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章