2024/4/18

81 阅读5分钟

命名空间

  1. 用于对类进行分类,相对于文件夹
  2. 通过用uing引入命名空间使用命名空间里的类
  3. 可以通过完整的路径,命名空间.类使用对应的类
  4. 命名空间可以嵌套
  5. internal表示在命名空间内部使用的类
  6. 解决了不同程序集之间方法命名冲突问题

C#常用命名空间 www.cnblogs.com/makesense/p…

字符串

String类

namespace _03_字符串
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string s = "www.sikiedu.com";
            Console.WriteLine(s.Length);
            //字符串==比较的是字符串本身每一个字符,相等才返回true,而像类,引用类型会判断地址是否相等
            Console.WriteLine(s == "www.sikiedu.com");
            //s引用改变了
            s = "http://" + s;
            
            Console.WriteLine(s[3]);

            Console.WriteLine(s.CompareTo("sikiedu"));//1

            Console.WriteLine(s.CompareTo("www.sikiedu.com"));//0

            Console.WriteLine(s.Replace(".","-dsf"));
            //返回一个字符串数组
            string[] vs = s.Split(".");
            foreach (string v in vs)
            {
                Console.WriteLine(v);
            }

            //从4位置截取字符串
            Console.WriteLine(s.Substring(4));
            //从4位置截取2个字符
            Console.WriteLine(s.Substring(4,2));

            //所有字符转为小写
            Console.WriteLine(s.ToLower());
            //所有字符转为大写
            Console.WriteLine(s.ToUpper());

            //把字符串前面和后面空格去掉,用于账号登录
            Console.WriteLine(s.Trim());

            //把字符串某一部分拷贝到字符数组
            char[] cA = new char[20];
            s.CopyTo(4, cA, 1, 7);
            foreach (char c in cA)
            {
                Console.WriteLine(c);
            }
            
            //静态方法,通过类调用
            //字符串连接
            Console.WriteLine(string.Concat("www","sikiedu.com"));


            int x = 23;
            int y = 545;
            int he = x + y;
            Console.WriteLine(string.Format(" {0}+{1}={2} {2}{1}", x, y, he));

            int money = 120000;
            //按人民币格式输出
            Console.WriteLine(string.Format("{0:C}", money));
            //保留2位小数,四舍五入
            Console.WriteLine(string.Format("{0:F2}", 23.123122));
            //百分比输出
            Console.WriteLine(string.Format("{0:P1}", 0.25657));
            //DateOnly只有年月  TimeOnly只有时间
            DateTime dt = System.DateTime.Now; 
            Console.WriteLine(string.Format("{0:yyyy-MM-dd HH:mm:ss}", dt));

            Console.WriteLine(dt.ToString("yyyy-MM-dd HH:mm:ss"));
            //查找字符的索引
            Console.WriteLine(s.IndexOf("."));
            //先找"."的索引,找不到再找"s"的索引
            Console.WriteLine(s.IndexOfAny(".s".ToCharArray()));
            //3位置插入字符串
            Console.WriteLine(s.Insert(3,"-----"));

            //把字符数组合并成字符串,合并时可以添加分隔的字符
            char[] cA1 = { 'A', 'B', 'C', 'D' };
            Console.WriteLine( string.Join("、",cA1));

        }
    }
}


字符串常用方法

  1. s.CompareTo() 比较字符串内容,相同返回0,不同返回1

  2. s.Replace() 替换字符串

StringBuilder

using System.Text;

namespace _04_字符串StringBuilder
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //StringBuilder是可变的,存储在堆里,类似字符数组,在频繁增删改字符串时候使用
            StringBuilder sb = new StringBuilder("www.sikiedu.com");

            sb.Append("123123");

            sb.Insert(3, " ");

            sb.Remove(4, 2);

            sb.Replace("i", "Love");

            Console.WriteLine(sb.ToString());

            //可以指定字符串容量,因为扩容会消耗性能
            StringBuilder sb2 = new StringBuilder(10);

            StringBuilder sb3 = new StringBuilder("www.sikiedu.com",10);

            Console.WriteLine(sb2.Capacity);


            
        }
    }
}

委托

  1. 同一个类的静态方法是可以直接访问的
namespace _06_委托
{
    internal class Program
    {
        delegate void IntMethodInvoker(int i);
        delegate void TwoLong(long a, long b);
        delegate string GetAString();
        delegate double DoubleOpDelegate(double x);
        static void Main(string[] args)
        {
            //IntMethodInvoker intvoker = null;
            //TwoLong twoLong = null;
            //intvoker = test;    //类内静态方法直接使用
            //intvoker(10);
            //if(twoLong != null)
            //{
            //    twoLong(2, 23);
            //}
            //int x = 123;
            //GetAString getAString = x.ToString;
            //GetAString getAString1 = new GetAString(x.ToString);
            //Console.WriteLine(getAString);
            DoubleOpDelegate[] operations = { MathOp.MultiplayByTwo, MathOp.Square };
            foreach (DoubleOpDelegate operation in operations)
            {
                Console.WriteLine(operation(3));

            }
            
            
        }

        private static void test(int i)
        {
            Console.WriteLine("我是哈哈哈"+i);
        }
    
        static void ProcessAndDisplayRes(DoubleOpDelegate op, double value)
        {
            double result = op(value);
            Console.WriteLine(result);

        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _06_委托
{
    internal class MathOp
    {
        public static double MultiplayByTwo(double value)
        {
            return value * 2;
        }
        public static double Square(double value)
        {
            return value * value;
        }
    }
}

Action委托

namespace _07_Action委托
{
    internal class Program
    {
        private static void  Test1()
        {
            Console.WriteLine("test1");
        }
        private static void Test2(int x)
        {
            Console.WriteLine("test2"+x);
        }
        private static void Test3(double x, int y)
        {
            Console.WriteLine("test3" + x + y);
        }
        static void Main(string[] args)
        {
            Action action = Test1;
            action();

            Action<int> method = Test2;
            method(124);

            Action<double,int> method2 = Test3;
            Test3(1, 2);
        }
    }
}

Func委托

namespace _08_Func委托
{
    internal class Program
    {
        private static string Test1()
        {
            return "ssss";
        }
        private static string Test2(int x, double y)
        {
            return "sss" + x + y;
        }
        static void Main(string[] args)
        {
            Func<string> f = Test1;
            Console.WriteLine(f);

            Func<int,double,string> f2 = Test2;
            Console.WriteLine(f2(1,2));
        }
    }
}

委托冒泡排序

namespace _09_委托冒泡排序
{
    internal class Program
    {
        //private static void Sort(int[] sortArray)
        //{
        //    bool swapped = true;
        //    do
        //    {
        //        swapped = false;
        //        for (int i = 0;i < sortArray.Length-1; i++)
        //        {
        //            if (sortArray[i] > sortArray[i + 1])
        //            {
        //                int temp = sortArray[i];
        //                sortArray[i] = sortArray[i + 1];
        //                sortArray[i + 1] = temp;
        //                swapped = true;
        //            }
        //        }
        //    } while (swapped);
        //}
        public static void Sort<T>(T[] array, Func<T, T, bool> compare)
        {
            bool swapped = true;
            do
            {
                swapped = false;
                for (int i = 0; i < array.Length - 1; i++)
                {
                    if (compare(array[i], array[i+1]))
                    {
                        T temp = array[i];
                        array[i] = array[i + 1];
                        array[i + 1] = temp;
                        swapped = true;
                    }
                }
            } while (swapped);
        }
         static void Main(string[] args)
        {
            Employee[] employees =
            {
                new Employee("Bunny",20000),
                new Employee("Mich",10000),
                new Employee("si",2000),
                new Employee("cc",1000),
                new Employee("Bunn",30000),
                new Employee("Bunny",20000),

            };

            Sort<Employee>(employees, Employee.CompareSalary);
            foreach (Employee employee in employees)
            {
                    Console.WriteLine(employee.Name+":"+employee.Salary);
            }
            
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _09_委托冒泡排序
{
    internal class Employee
    {
        public string Name {  get; private set; }
        public double Salary {  get; private set; }

        public Employee(string name, double salary)
        {
            Name = name;
            Salary = salary;
        }
        public static bool CompareSalary(Employee a, Employee b)
        {
            return a.Salary > b.Salary;
        }
    }
}

多播委托

namespace _10_多播委托
{
    internal class Program
    {
        public static void Test1()
        {
            Console.WriteLine("Test1");
        }
        public static void Test2() 
        { 
            Console.WriteLine("Test2"); 
        }
        static void Main(string[] args)
        {
            Action action1 = Test1;
            action1 += Test2; //action1 = action1 + Test2;
            action1();

            action1 -= Test1;
            action1();
            action1 += Test2;

            //Delegate类,大写是定义通用的委托
            Delegate[] delegates = action1.GetInvocationList();//得到action1委托数组
            foreach (Delegate d in delegates)
            {
                d.DynamicInvoke();//动态调用委托方法
            }

        }
    }
}

匿名方法

namespace _11_匿名方法
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //匿名方法适用代码量小的,方便不定义方法直接赋值给委托
            Func<int, int, int> plus = delegate (int a, int b) { return a+b; };
            
            



            //这里已经用Func定义委托,明显已经知道是委托类型了,所以这里关键子delegate多余了,int类型也已经知道了
            //Lambda表达式简化匿名方法
            Func<int, int, int> f2 = (a, b) => {  return a + b; };
            Func<int, int, int> f1 = (a, b) => a + b;
            
            Func<int, int, int> p = (a, b) => plus(a, b);
            
            //单个参数,不用加括号
            Func<double, double> square = x=>x*x;
            int res = plus(1, 2);
            Console.WriteLine(res);
            //Lambda表达式外部的变量可以影响到内部函数返回结果
            //方法体内,可以访问到外部变量,会受到外部变量的影响
            int a = 1;
            Func<int, int> f = x => x+a;
            Console.WriteLine(f(2));

            a = 2;
            Console.WriteLine(f(2));

            

            
        }
    }
}

委托和事件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _12_工具人下楼
{
    delegate void DownStairDelegate();
    internal class ToolMan
    {
        public string Name { get; private set; }
        //声明一个受限制的委托,委托只能加减,不能赋值,这个就是事件,受到限制的委托 
        public event DownStairDelegate DownStairDelegate = null;
        public ToolMan(string name)
        {
            Name = name;
        }

        public  void DownStair()
        {
            Console.WriteLine("工具人下楼了");
            if(DownStairDelegate != null )
            {
                DownStairDelegate();
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _12_工具人下楼
{
    internal class LazyMan
    {
        public string Name { get; private set; }

        public LazyMan(string name)
        {
            Name = name;
        }

        public void TakeFood()
        {
            Console.WriteLine("给"+ Name + "拿外卖");
        }

        public void TakePackage()
        {
            Console.WriteLine("给" + Name + "拿快递");
        }
    }
}
namespace _12_工具人下楼
{
    internal class Program
    {
        static void Main(string[] args)
        {
            ToolMan toolMan = new ToolMan("小工具人");

            LazyMan lazyMan1 = new LazyMan("张三");
            LazyMan lazyMan2 = new LazyMan("李四");
            LazyMan lazyMan3 = new LazyMan("王五");

            //工具人下楼
            toolMan.DownStair();

            //订阅消息
            toolMan.DownStairDelegate += lazyMan1.TakeFood;
            toolMan.DownStairDelegate += lazyMan2.TakePackage;
            toolMan.DownStairDelegate += lazyMan3.TakeFood;

            //这样只要调用下楼函数,委托如果不为空,就全部调用,多播委托
            toolMan.DownStair();
            //但是现在有问题,比如可以直接越过工具人下楼方法,直接调用toolMan.DownStairDelegate()下楼

            //解决方法直接在委托前面加一个事件event

        }
    }
}