C#高级学习1

加密解密

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

namespace MyNet
{
    public class CommonMethod
    {
        /// 因为方法声明的时候,写死了参数类型,性能高,代码冗余
        public static void ShowInt(int iParameter)
        {
            Console.WriteLine("This is {0},parameter={1},type={2}",
                //打印类名                    打印参数类型              参数
                //This is CommonMethod,parameter=Int32,type=123
                typeof(CommonMethod).Name, iParameter.GetType().Name, iParameter);
               //typeof 拿到方法名   MyNet.CommonMethod
        }
        public static void ShowString(string sParameter)
        {
            Console.WriteLine("This is {0},parameter={1},type={2}",
                typeof(CommonMethod).Name, sParameter.GetType().Name, sParameter);
        }
        public static void ShowDateTime(DateTime dtParameter)
        {
            Console.WriteLine("This is {0},parameter={1},type={2}",
                typeof(CommonMethod).Name, dtParameter.GetType().Name, dtParameter);
        }

        /// 打印个object值
        /// 1 object类型是一切类型的父类
        /// 2 通过继承,子类拥有父类的一切属性和行为;任何父类出现的地方,都可以用子类来代替
        /// object引用类型  加入传个值类型int  会有装箱拆箱  性能损失
        /// 类型不安全
        public static void ShowObject(object oParameter)
        {
            Console.WriteLine("This is {0},parameter={1},type={2}",
                typeof(CommonMethod), oParameter.GetType().Name, oParameter);
        }



        //现在会使用占位符,性能和定义变量差不多。
        public static void GenericShow(T tParameter)
        {
            Console.WriteLine("This is {0},parameter={1},type={2}",
                "GenericMethod", tParameter.GetType().Name, tParameter.ToString());
        }
    }
}

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

namespace MyNet
{
    /// 
    /// 1 引入泛型:延迟声明
    /// 2 如何声明和使用泛型
    /// 3 泛型的好处和原理
    /// 4 泛型类、泛型方法、泛型接口、泛型委托
    /// 5 泛型约束
    /// 6 协变 逆变(选修)
    /// 7 泛型缓存(选修)(为每一种类型创建一个缓存)
    /// 
    class Program
    {
        static void Main(string[] args)
        {
           
            int intValue = 123;
            string stringValue = "this is string";
            DateTime dtValue = DateTime.Now;

            object objValue = "this is objstring";

            1.0
            //CommonMethod.ShowInt(intValue);
            //CommonMethod.ShowString(stringValue);
            //CommonMethod.ShowDateTime(dtValue);

            //2.0
            //CommonMethod.ShowObject(intValue);
            //CommonMethod.ShowObject(stringValue);
            //CommonMethod.ShowObject(dtValue);


            //3.0
            CommonMethod.GenericShow(intValue);
            CommonMethod.GenericShow(stringValue);
            CommonMethod.GenericShow(dtValue);
            CommonMethod.GenericShow(objValue);

        }   }
}

 
  

泛型类、泛型接口、泛型委托

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

namespace MyGeneric
{
    /// 一个类来满足不同的具体类型,做相同的事儿
    public class GenericClass
    {
        public T _T;
    }
    ///  一个接口来满足不同的具体类型的接口,做相同的事儿
    public interface IGenericInterface //where T : People
    {
        T GetT(T t);//泛型类型的返回值
    }

    public delegate void SayHi(T t);//泛型委托
}


public class CommonClass:xxx  
    //继承泛型类必须指定类型,接口也一样
    
 //泛型约束
 public class student where T:Person
 //接口约束   where T:ISports 借口约束
 //值类型约束 where T:struct
 //无参数构造函数约束 where T:new() 
default(T);//根据不同的类型赋予默认值


泛型选修
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyGeneric.Extend
{
    /// 
    /// .net4.0
    /// 只能放在接口或者委托的泛型参数前面
    /// out 协变covariant    修饰返回值 
    /// in  逆变contravariant  修饰传入参数
    /// 
    public class CCTest
    {
        public static void Show()
        {
            {
                Bird bird1 = new Bird();
                Bird bird2 = new Sparrow();
                Sparrow sparrow1 = new Sparrow();
                //Sparrow sparrow2 = new Bird(); 不可以
            }

            {
                List birdList1 = new List();
                //List birdList2 = new List();
                //应该可以呀   一堆麻雀当然是一堆鸟
                //没有父子关系

                List birdList3 = new List().Select(c => (Bird)c).ToList();
            }
            
            
            {   //协变
                IEnumerable birdList1 = new List();
                IEnumerable birdList2 = new List();

                Func func = new Func(() => null);

                ICustomerListOut customerList1 = new CustomerListOut();
                ICustomerListOut customerList2 = new CustomerListOut();
            }



            {//逆变
                ICustomerListIn customerList2 = new CustomerListIn();
                ICustomerListIn customerList1 = new CustomerListIn();

                ICustomerListIn birdList1 = new CustomerListIn();
                birdList1.Show(new Sparrow());
                birdList1.Show(new Bird());

                Action act = new Action((Bird i) => { });
            }


            {
                IMyList myList1 = new MyList();
                IMyList myList2 = new MyList();//协变
                IMyList myList3 = new MyList();//逆变
                IMyList myList4 = new MyList();//逆变+协变
            }
        }
    }

    public class Bird
    {
        public int Id { get; set; }
    }
    public class Sparrow : Bird
    {
        public string Name { get; set; }
    }

    public interface ICustomerListIn
    {
        //T Get();

        void Show(T t);
    }

    public class CustomerListIn : ICustomerListIn
    {
        //public T Get()
        //{
        //    return default(T);
        //}

        public void Show(T t)
        {
        }
    }

    /// 
    /// out 协变 只能是返回结果
    /// 
    /// 
    public interface ICustomerListOut
    {
        T Get();

        //void Show(T t);
    }

    public class CustomerListOut : ICustomerListOut
    {
        public T Get()
        {
            return default(T);
        }

        //public void Show(T t)
        //{

        //}
    }





    public interface IMyList
    {
        void Show(inT t);
        outT Get();
        outT Do(inT t);

        out 只能是返回值   in只能是参数
        //void Show1(outT t);
        //inT Get1();

    }

    public class MyList : IMyList
    {

        public void Show(T1 t)
        {
            Console.WriteLine(t.GetType().Name);
        }

        public T2 Get()
        {
            Console.WriteLine(typeof(T2).Name);
            return default(T2);
        }

        public T2 Do(T1 t)
        {
            Console.WriteLine(t.GetType().Name);
            Console.WriteLine(typeof(T2).Name);
            return default(T2);
        }
    }

}

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

namespace MyGeneric.Extend
{
    public class GenericCacheTest
    {
        public static void Show()
        {
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine(GenericCache.GetCache());
                Thread.Sleep(10);
                Console.WriteLine(GenericCache.GetCache());
                Thread.Sleep(10);
                Console.WriteLine(GenericCache.GetCache());
                Thread.Sleep(10);
                Console.WriteLine(GenericCache.GetCache());
                Thread.Sleep(10);
                Console.WriteLine(GenericCache.GetCache());
                Thread.Sleep(10);
            }



        }
    }

    /// 
    /// 字典缓存:静态属性常驻内存
    /// 
    public class DictionaryCache
    {
        private static Dictionary _TypeTimeDictionary = null;
        static DictionaryCache()
        {
            Console.WriteLine("This is DictionaryCache 静态构造函数");
            _TypeTimeDictionary = new Dictionary();
        }
        public static string GetCache()
        {
            Type type = typeof(Type);
            if (!_TypeTimeDictionary.ContainsKey(type))
            {
                _TypeTimeDictionary[type] = string.Format("{0}_{1}", typeof(T).FullName, DateTime.Now.ToString("yyyyMMddHHmmss.fff"));
            }
            return _TypeTimeDictionary[type];
        }
    }


    /// 
    /// 每个不同的T,都会生成一份不同的副本
    /// 适合不同类型,需要缓存一份数据的场景,效率高
    /// 不能主动释放
    /// 
    /// 
    public class GenericCache
    {
        static GenericCache()
        {
            Console.WriteLine("This is GenericCache 静态构造函数");
            _TypeTime = string.Format("{0}_{1}", typeof(T).FullName, DateTime.Now.ToString("yyyyMMddHHmmss.fff"));
        }

        private static string _TypeTime = "";

        public static string GetCache()
        {
            return _TypeTime;
        }
    }

}

反射

加载dll,打印信息

   
                Console.WriteLine("************************Common*****************");
                IDBHelper iDBHelper = new MySqlHelper();
                iDBHelper.Query();

                Console.WriteLine("************************Reflection*****************");
                Assembly assembly = Assembly.Load("Ruanmou.DB.MySql");//dll名称无后缀  从当前目录加载  1 加载dll
                //Assembly assembly1 = Assembly.LoadFile(@"D:\ruanmou\online11\20180425Advanced11Course2Reflection\MyReflection\MyReflection\bin\Debug\Ruanmou.DB.MySql.dll");
                //完整路径的加载  可以是别的目录   加载不会错,但是如果没有依赖项,使用的时候会错
                Assembly assembly2 = Assembly.LoadFrom("Ruanmou.DB.MySql.dll");//带后缀或者完整路径

                foreach (var item in assembly.GetModules())
                {
                    Console.WriteLine(item.FullyQualifiedName);
                    //D:\BaiduNetdiskDownload\第01部分-NET高级开发7个专题课(71课时)\08、课程代码+课件\03-Reflection\MyReflection\MyReflection\bin\Debug\Ruanmou.DB.MySql.dll
                }

                foreach (var item in assembly.GetTypes())
                {
                    Console.WriteLine(item.FullName);
                    //Ruanmou.DB.MySql.MySqlHelper
                }

Factory 进行封装,不需要重新编译程序,可修改配置文件。实现程序可配置可扩展,如把Oracle.dll放入目录,更改配置文件即可使用

// IOC

                Console.WriteLine("**********Reflection+Factory+config*****************");
                IDBHelper iDBHelper = Factory.CreateHelper();
                iDBHelper.Query();
using Ruanmou.DB.Interface;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace MyReflection
{
    /// 
    /// 创建对象
    /// 
    public  class Factory
    {

        //这里异常,会导致方法进入不了
        private static string IDBHelperConfig = ConfigurationManager.AppSettings["IDBHelperConfig"];
        private static string DllName = IDBHelperConfig.Split(',')[1];
        private static string TypeName = IDBHelperConfig.Split(',')[0];


        public static IDBHelper CreateHelper()//1 2
        {
            Assembly assembly = Assembly.Load(DllName);//1 加载dll
            Type type = assembly.GetType(TypeName);//2 获取类型信息
            object oDBHelper = Activator.CreateInstance(type);//3 创建对象
            IDBHelper iDBHelper = (IDBHelper)oDBHelper;//4 类型转换
            return iDBHelper;
        }
    }
}

反射+Oobject

1.破坏单例函数

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

namespace Ruanmou.DB.SqlServer
{
    /// 
    /// 单例模式
    /// 
    public sealed class Singleton
    {
        private static Singleton _Singleton = null;
        private Singleton()
        {
            Console.WriteLine("Singleton被构造");
        }

        static Singleton()
        {
            _Singleton = new Singleton();
        }

        public static Singleton GetInstance()
        {
            return _Singleton;
        }
    }
}

                Console.WriteLine("**********Reflection+Obeject*****************");
                
                Singleton singleton = Singleton.GetInstance();
                Singleton singleton1 = Singleton.GetInstance();
                Singleton singleton2 = Singleton.GetInstance();

                Assembly assembly = Assembly.Load("Ruanmou.DB.SqlServer");
                Type type = assembly.GetType("Ruanmou.DB.SqlServer.Singleton");
                //破坏单例,调用构造函数
                Singleton singleton3 = (Singleton)Activator.CreateInstance(type,true);
                Singleton singleton4 = (Singleton)Activator.CreateInstance(type, true);
                Singleton singleton5 = (Singleton)Activator.CreateInstance(type, true);

调用无参,不同参数的构造函数

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

namespace Ruanmou.DB.SqlServer
{
    /// 
    /// 反射测试类
    /// 
    public class ReflectionTest
    {
        #region Identity
        /// 
        /// 无参构造函数
        /// 
        public ReflectionTest()
        {
            Console.WriteLine("这里是{0}无参数构造函数", this.GetType());
        }

        /// 
        /// 带参数构造函数
        /// 
        /// 
        public ReflectionTest(string name)
        {
            Console.WriteLine("这里是{0} 有参数构造函数", this.GetType());
        }

        public ReflectionTest(int id)
        {
            Console.WriteLine("这里是{0} 有参数构造函数", this.GetType());
        }
        #endregion

        #region Method
        /// 
        /// 无参方法
        /// 
        public void Show1()
        {
            Console.WriteLine("这里是{0}的Show1", this.GetType());
        }
        /// 
        /// 有参数方法
        /// 
        /// 
        public void Show2(int id)
        {

            Console.WriteLine("这里是{0}的Show2", this.GetType());
        }
        /// 
        /// 重载方法之一
        /// 
        /// 
        /// 
        public void Show3(int id, string name)
        {
            Console.WriteLine("这里是{0}的Show3", this.GetType());
        }
        /// 
        /// 重载方法之二
        /// 
        /// 
        /// 
        public void Show3(string name, int id)
        {
            Console.WriteLine("这里是{0}的Show3_2", this.GetType());
        }
        /// 
        /// 重载方法之三
        /// 
        /// 
        public void Show3(int id)
        {

            Console.WriteLine("这里是{0}的Show3_3", this.GetType());
        }
        /// 
        /// 重载方法之四
        /// 
        /// 
        public void Show3(string name)
        {

            Console.WriteLine("这里是{0}的Show3_4", this.GetType());
        }
        /// 
        /// 重载方法之五
        /// 
        public void Show3()
        {

            Console.WriteLine("这里是{0}的Show3_1", this.GetType());
        }
        /// 
        /// 私有方法
        /// 
        /// 
        private void Show4(string name)
        {
            Console.WriteLine("这里是{0}的Show4", this.GetType());
        }
        /// 
        /// 静态方法
        /// 
        /// 
        public static void Show5(string name)
        {
            Console.WriteLine("这里是{0}的Show5", typeof(ReflectionTest));
        }
        #endregion
    }
}

                Console.WriteLine("**********Reflection+Obeject*****************");
                Assembly assembly = Assembly.Load("Ruanmou.DB.SqlServer");
                Type type = assembly.GetType("Ruanmou.DB.SqlServer.ReflectionTest");
                //无参的构造函数
                object oReflectionTest1 = Activator.CreateInstance(type);
                object oReflectionTest2 = Activator.CreateInstance(type,new object[] { 123});
                object oReflectionTest3 = Activator.CreateInstance(type, new object[] { "123" });

调用泛型类

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

namespace Ruanmou.DB.SqlServer
{
    public class GenericClass
    {
        public void Show(T t, W w, X x)
        {
            Console.WriteLine("t.type={0},w.type={1},x.type={2}", t.GetType().Name, w.GetType().Name, x.GetType().Name);
        }
    }

    public class GenericMethod
    {
        public void Show(T t, W w, X x)
        {
            Console.WriteLine("t.type={0},w.type={1},x.type={2}", t.GetType().Name, w.GetType().Name, x.GetType().Name);
        }
    }

    public class GenericDouble
    {
        public void Show(T t, W w, X x)
        {
            Console.WriteLine("t.type={0},w.type={1},x.type={2}", t.GetType().Name, w.GetType().Name, x.GetType().Name);
        }
    }
}

                Assembly assembly = Assembly.Load("Ruanmou.DB.SqlServer");
                Type type = assembly.GetType("Ruanmou.DB.SqlServer.GenericClass`3");
                //object oGeneric = Activator.CreateInstance(type);
                Type newType = type.MakeGenericType(new Type[] { typeof(int), typeof(string), typeof(DateTime) });
                object oGeneric = Activator.CreateInstance(newType);

反射+方法

URL地址用反射,找到类名拼接

// 反射+方法
                Assembly assembly = Assembly.Load("Ruanmou.DB.SqlServer");
                Type type = assembly.GetType("Ruanmou.DB.SqlServer.ReflectionTest");
                object oReflectionTest = Activator.CreateInstance(type);


                MethodInfo methodInfo = type.GetMethod("Show1");
                //传入实例和参数 调用无参方法 Invoke函数也是一个反射的实现
                methodInfo.Invoke(oReflectionTest, null);


                methodInfo = type.GetMethod("Show2");
                //传入实例和参数 调用int方法 
                methodInfo.Invoke(oReflectionTest, new object[] { 123 });

                methodInfo = type.GetMethod("Show5");
                //实例可为null和参数 调用静态方法方法 
                methodInfo.Invoke(oReflectionTest, new object[]{"string"});
                methodInfo.Invoke(null, new object[] { "string" });




                //调用重载方法中无参方法
                methodInfo = type.GetMethod("Show3", new Type[] { });
                methodInfo.Invoke(oReflectionTest,new object[] { });

                //调用重载方法中int方法
                methodInfo = type.GetMethod("Show3", new Type[] { typeof(int)});
                methodInfo.Invoke(oReflectionTest, new object[] { 123});

                //调用重载方法中多参数方法
                methodInfo = type.GetMethod("Show3", new Type[] { typeof(int),typeof(string) });
                methodInfo.Invoke(oReflectionTest, new object[] { 123,"string" });


                //调用private方法
                MethodInfo methodInfo = type.GetMethod("Show4",BindingFlags.Instance|BindingFlags.NonPublic);
          
                methodInfo.Invoke(oReflectionTest,new object[] { "你好" });

                //调用泛型方法!!!
               
                Assembly assembly = Assembly.Load("Ruanmou.DB.SqlServer");

                Type typeGenericDouble = assembly.GetType("Ruanmou.DB.SqlServer.GenericDouble`1");
                Type newType = typeGenericDouble.MakeGenericType(new Type[] { typeof(int) });
                object oGeneric = Activator.CreateInstance(newType);
                MethodInfo method = newType.GetMethod("Show");
                MethodInfo methodNew = method.MakeGenericMethod(new Type[] { typeof(string), typeof(DateTime) });
                methodNew.Invoke(oGeneric, new object[] { 123, "流浪诗人", DateTime.Now });

//不知道方法名可以调用一下
foreach(var item in type.GetMethods())
{
    Console.WriteLine(item.Name);
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ruanmou.DB.SqlServer
{
    /// 
    /// 反射测试类
    /// 
    public class ReflectionTest
    {
        #region Identity
        /// 
        /// 无参构造函数
        /// 
        public ReflectionTest()
        {
            Console.WriteLine("这里是{0}无参数构造函数", this.GetType());
        }

        /// 
        /// 带参数构造函数
        /// 
        /// 
        public ReflectionTest(string name)
        {
            Console.WriteLine("这里是{0} 有参数构造函数", this.GetType());
        }

        public ReflectionTest(int id)
        {
            Console.WriteLine("这里是{0} 有参数构造函数", this.GetType());
        }
        #endregion

        #region Method
        /// 
        /// 无参方法
        /// 
        public void Show1()
        {
            Console.WriteLine("这里是{0}的Show1", this.GetType());
        }
        /// 
        /// 有参数方法
        /// 
        /// 
        public void Show2(int id)
        {

            Console.WriteLine("这里是{0}的Show2", this.GetType());
        }
        /// 
        /// 重载方法之一
        /// 
        /// 
        /// 
        public void Show3(int id, string name)
        {
            Console.WriteLine("这里是{0}的Show3", this.GetType());
        }
        /// 
        /// 重载方法之二
        /// 
        /// 
        /// 
        public void Show3(string name, int id)
        {
            Console.WriteLine("这里是{0}的Show3_2", this.GetType());
        }
        /// 
        /// 重载方法之三
        /// 
        /// 
        public void Show3(int id)
        {

            Console.WriteLine("这里是{0}的Show3_3", this.GetType());
        }
        /// 
        /// 重载方法之四
        /// 
        /// 
        public void Show3(string name)
        {

            Console.WriteLine("这里是{0}的Show3_4", this.GetType());
        }
        /// 
        /// 重载方法之五
        /// 
        public void Show3()
        {

            Console.WriteLine("这里是{0}的Show3_1", this.GetType());
        }
        /// 
        /// 私有方法
        /// 
        /// 
        private void Show4(string name)
        {
            Console.WriteLine("这里是{0}的Show4", this.GetType());
        }
        /// 
        /// 静态方法
        /// 
        /// 
        public static void Show5(string name)
        {
            Console.WriteLine("这里是{0}的Show5", typeof(ReflectionTest));
        }
        #endregion
    }
}

操作字段

                //以前的做法,操作字段
                Console.WriteLine("************************Reflection+Property/Field*****************");
                People people = new People();
                people.Id = 123;
                people.Name = "Lutte";
                people.Description = "高级班的新学员";

                Console.WriteLine($"people.Id={people.Id}");
                Console.WriteLine($"people.Name={people.Name}");
                Console.WriteLine($"people.Description={people.Description}");
                Console.WriteLine("****************以前的方法*****************");
                
                Type type = typeof(People);
                object oPeople = Activator.CreateInstance(type);

                foreach (var prop in type.GetProperties())
                {
                   // Console.WriteLine(type.Name); //类名
                    //Console.WriteLine(prop.Name); //拿到属性值
                   // Console.WriteLine(prop.GetValue(oPeople)); //GetValue()是用来获取指定对象的属性值的
                    if (prop.Name.Equals("Id"))
                    {
                        prop.SetValue(oPeople, 234);
                    }
                    else if (prop.Name.Equals("Name"))
                    {
                        prop.SetValue(oPeople, "风潇潇");
                    }
                    Console.WriteLine($"{type.Name}.{prop.Name}={prop.GetValue(oPeople)}");
                  
                }

//操作字段

            foreach (var field in type.GetFields())
                {

     
                    if (field.Name.Equals("Description"))
                    {
                        field.SetValue(oPeople, "这是个帅哥");
                    }
                   
                }

利用反射给对象赋值!!

              People people = new People();
                people.Id = 123;
                people.Name = "Lutte";
                people.Description = "高级班的新学员";

                //假设我们从数据库拿到一个People对象,给PeopleDTO对象赋值

                Type typePeople = typeof(People);
                //PeopleDTO 有id、name、description
                Type typePeopleDTO = typeof(PeopleDTO);

                object peopleDTO = Activator.CreateInstance(typePeopleDTO);
            //自动给属性赋值
                foreach (var prop in typePeopleDTO.GetProperties())
                {

                    object value = typePeople.GetProperty(prop.Name).GetValue(people);
                    prop.SetValue(peopleDTO, value);
                }
                //自动给字段赋值
                foreach (var filed in typePeopleDTO.GetFields())
                {

                    object value = typePeople.GetField(filed.Name).GetValue(people);
                    filed.SetValue(peopleDTO, value);
                }

特性Attribute

//常见的特性
[Obsolete("这个函数已过期")] //生成警告
[Obsolete("这个函数已过期"),true] //生成错误
[Serializable] //可以序列化和反序列化

利用反射查看特性

using MyAttribute.Extension;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace MyAttribute
{
    public class Manager
    {
        public static void Show(Student student)
        {
            Type type = typeof(Student); //student.GetType();
            if (type.IsDefined(typeof(CustomAttribute), true))//检查有没有特性  性能高
            {
                CustomAttribute attribute = (CustomAttribute)type.GetCustomAttribute(typeof(CustomAttribute), true);
                Console.WriteLine($"{attribute.Description}_{attribute.Remark}");
                attribute.Show();
            }

            PropertyInfo property = type.GetProperty("Id");
            if (property.IsDefined(typeof(CustomAttribute), true))
            {
                CustomAttribute attribute = (CustomAttribute)property.GetCustomAttribute(typeof(CustomAttribute), true);
                Console.WriteLine($"{attribute.Description}_{attribute.Remark}");
                attribute.Show();
            }

            MethodInfo method = type.GetMethod("Answer");
            if (method.IsDefined(typeof(CustomAttribute), true))
            {
                CustomAttribute attribute = (CustomAttribute)method.GetCustomAttribute(typeof(CustomAttribute), true);
                Console.WriteLine($"{attribute.Description}_{attribute.Remark}");
                attribute.Show();
            }

            ParameterInfo parameter = method.GetParameters()[0];
            if (parameter.IsDefined(typeof(CustomAttribute), true))
            {
                CustomAttribute attribute = (CustomAttribute)parameter.GetCustomAttribute(typeof(CustomAttribute), true);
                Console.WriteLine($"{attribute.Description}_{attribute.Remark}");
                attribute.Show();
            }

            ParameterInfo returnParameter = method.ReturnParameter;
            if (returnParameter.IsDefined(typeof(CustomAttribute), true))
            {
                CustomAttribute attribute = (CustomAttribute)returnParameter.GetCustomAttribute(typeof(CustomAttribute), true);
                Console.WriteLine($"{attribute.Description}_{attribute.Remark}");
                attribute.Show();
            }

        }
    }
}

特性写法

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

namespace MyAttribute
{
    /// 
    /// 特性:就是一个类,可以有构造函数、属性、委托、事件,直接/间接继承自attribute
    ///       一般以Attribute结尾,声明时候可以省略掉,
    /// 
    /// AttributeTargets是一个枚举,可以指定修饰什么元素     AllowMultiple允许特性重复修饰  Inherited特性是否可以继承
    [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
    
    public class CustomAttribute : Attribute
    {
        public CustomAttribute()
        { }

        public CustomAttribute(int id)
        {
            Console.WriteLine("********************");
        }


        public string Description { get; set; }

        public string Remark = null;

        public void Show()
        {
            Console.WriteLine($"This is {nameof(CustomAttribute)}");
        }

       

    }
}

特性一定要通过反射调用!

例子 :根据状态码0,1,2,反射成中文状态正常,冻结,删除

主函数

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

namespace MyAttribute
{
    /// 
    /// 1 特性attribute,和注释有什么区别
    /// 2 声明和使用attribute,AttributeUsage
    /// 3 运行中获取attribute:额外信息 额外操作
    /// 4 Remark封装、attribute验证
    /// 5 作业部署
    /// 
    /// 特性:中括号声明 
    /// 
    /// 错觉:每一个特性都可以带来对应的功能
    /// 
    /// 实际上特性添加后,编译会在元素内部产生IL,但是我们是没办法直接使用的,
    /// 而且在metadata里面会有记录
    /// 
    /// 特性,本身是没用的
    /// 程序运行的过程中,我们能找到特性,而且也能应用一下
    /// 任何一个可以生效的特性,都是因为有地方主动使用了的
    /// 
    /// 没有破坏类型封装的前提下,可以加点额外的信息和行为
    /// 
    class Program
    {
        
        static void Main(string[] args)
        {
            try
            {



                   //以前的写法 状态码0 正常 1冻结
                    UserState userState = UserState.Normal;
                    //if (userState == UserState.Normal)
                    //{
                    //    Console.WriteLine("正常状态");
                    //}
                    //else if (userState == UserState.Frozen)
                    //{ }
                    //else
                    //{ }
                    Console.WriteLine(userState.GetRemark());
                    Console.WriteLine(RemarkExtension.GetRemark(userState));
                    Console.WriteLine(UserState.Frozen.GetRemark());
                    Console.WriteLine(UserState.Deleted.GetRemark());

        
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.Read();
        }
    }
}

反射+特性

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

namespace MyAttribute.Extension
{
    /// 
    /// 用户状态
    /// 
    public enum UserState
    {
        /// 
        /// 正常
        /// 
        [Remark("正常")]
        Normal = 0,//左边是字段名称  右边是数据库值   哪里放描述?  注释
        /// 
        /// 冻结
        /// 
        [Remark("冻结")]
        Frozen = 1,
        /// 
        /// 删除
        /// 
        //[Remark("删除")]
        Deleted = 2
    }
    //枚举项加一个描述   实体类的属性也可以Display  
    //别名   映射  
    public class RemarkAttribute : Attribute
    {
        public RemarkAttribute(string remark)
        {
            this._Remark = remark;
        }
        private string _Remark = null;
        public string GetRemark()
        {
            return this._Remark;
        }
    }


    public static class RemarkExtension
    {
        public static string GetRemark(this Enum value)
        {
            Type type = value.GetType();
            FieldInfo field = type.GetField(value.ToString());
            if (field.IsDefined(typeof(RemarkAttribute), true))
            {
                RemarkAttribute attribute = (RemarkAttribute)field.GetCustomAttribute(typeof(RemarkAttribute), true);
                return attribute.GetRemark();
            }
            else
            {
                return value.ToString();
            }
        }

    }
}

利用特性限制属性

            //以前写法,在类中进行限定,导致模型和方法耦合
            //if(student.QQ > 10001 && student.QQ < 999999999)
            //    {
            //    Console.WriteLine();
            //    }
            //else if(....)
            //    { 
            //    }

main函数

                Student student = new Student();
                student.Id = 123;
                student.Name = "小张";

                student.QQ = 123456;

                Manager.Show(student);

                student.QQ = 999;
                Manager.Show(student);

student类标记特性

        [LongAttribute(10001,999999)]
        public long QQ { get; set; }

调用反射

    public class Manager
    {
        public static void Show(Student student)
        {
            student.Validate();
        }
    }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace MyAttribute.Extension
{
    //反射
    public static  class ValidateExtension
    {
        public static bool Validate(this object oObject) 
        {
            Type type = oObject.GetType();
            foreach (var prop in type.GetProperties())
            {
                //如果是带有特性的实例
                if (prop.IsDefined(typeof(LongAttribute),true))
                    {  
                    
                    //拿到特性
                    LongAttribute attribute = (LongAttribute)prop.GetCustomAttribute(typeof(LongAttribute), true);
                        //利用特性判断值是否合法
                    if (!attribute.Validate(prop.GetValue(oObject))) 
                        {
                            return false;
                        }
                    }
            }
            return true;
        
        }

    }


    //特性
    public class LongAttribute : Attribute
    {
        private long _Min = 0;
        private long _Max = 0;
        public LongAttribute(long min, long max)
        {
            this._Min = min;
            this._Max = max;
        }

        public bool Validate(object value)//" "
        {
            //可以改成一句话
            if (value != null && !string.IsNullOrWhiteSpace(value.ToString()))
            {
                if (long.TryParse(value.ToString(), out long lResult))
                {
                    if (lResult > this._Min && lResult < this._Max)
                    {
                        return true;
                    }
                }
            }
            return false;
        }
    }
}

委托
 //把方法包装成对象,invoke的时候自动执行方法
                NoReturnNoPara method = new NoReturnNoPara(this.DoNothing);//2 委托的实例化
                method.Invoke();//3 委托实例的调用 method()和method.Invoke() 等价
                
                this.DoNothing();
 //传统方法1
            List studentList = this.GetStudentList();
            {
                //找出年龄大于25
                List result = new List();//准备容器
                foreach (Student student in studentList)//遍历数据源
                {
                    if (student.Age > 25)//判断条件
                    {
                        result.Add(student);//满足条件的放入容器
                    }
                }
                Console.WriteLine($"结果一共有{result.Count()}个");
            }

            {
                //传统方法
                //找出Name长度大于2
                List result = new List();
                foreach (Student student in studentList)
                {
                    if (student.Name.Length > 2)
                    {
                        result.Add(student);
                    }
                }
                Console.WriteLine($"结果一共有{result.Count()}个");
            }

            {
                //找出Name长度大于2 而且年龄大于25 而且班级id是2
                List result = new List();
                foreach (Student student in studentList)
                {
                    if (student.Name.Length > 2 && student.Age > 25 && student.ClassId == 2)
                    {
                        result.Add(student);
                    }
                }
                Console.WriteLine($"结果一共有{result.Count()}个");
            }

       //传统方法2 ,代码重用了,多分支维护难
private List GetList(List source, int type)
        {
            List result = new List();
            foreach (Student student in source)
            {
                if (type == 1)
                {
                    if (student.Age > 25)//判断条件
                    {
                        result.Add(student);//满足条件的放入容器
                    }
                }
                else if (type == 2)
                {
                    if (student.Name.Length > 2)
                    {
                        result.Add(student);
                    }
                }
                else if (type == 3)
                {
                    if (student.Name.Length > 2 && student.Age > 25 && student.ClassId == 2)
                    {
                        result.Add(student);
                    }
                }
            }
            return result;
        }

委托实现代码复用

//调用测试方法
ListExtend test =new ListExtend()
test.Show()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyDelegateEvent.DelegateExtend
{
    public class ListExtend
    {
        #region 数据准备
        /// 
        /// 准备数据
        /// 
        /// 
        private List GetStudentList()
        {
            #region 初始化数据
            List studentList = new List()
            {
                new Student()
                {
                    Id=1,
                    Name="老K",
                    ClassId=2,
                    Age=35
                },
                new Student()
                {
                    Id=1,
                    Name="hao",
                    ClassId=2,
                    Age=23
                },
                 new Student()
                {
                    Id=1,
                    Name="大水",
                    ClassId=2,
                    Age=27
                },
                 new Student()
                {
                    Id=1,
                    Name="半醉人间",
                    ClassId=2,
                    Age=26
                },
                new Student()
                {
                    Id=1,
                    Name="风尘浪子",
                    ClassId=2,
                    Age=25
                },
                new Student()
                {
                    Id=1,
                    Name="一大锅鱼",
                    ClassId=2,
                    Age=24
                },
                new Student()
                {
                    Id=1,
                    Name="小白",
                    ClassId=2,
                    Age=21
                },
                 new Student()
                {
                    Id=1,
                    Name="yoyo",
                    ClassId=2,
                    Age=22
                },
                 new Student()
                {
                    Id=1,
                    Name="冰亮",
                    ClassId=2,
                    Age=34
                },
                 new Student()
                {
                    Id=1,
                    Name="瀚",
                    ClassId=2,
                    Age=30
                },
                new Student()
                {
                    Id=1,
                    Name="毕帆",
                    ClassId=2,
                    Age=30
                },
                new Student()
                {
                    Id=1,
                    Name="一点半",
                    ClassId=2,
                    Age=30
                },
                new Student()
                {
                    Id=1,
                    Name="小石头",
                    ClassId=2,
                    Age=28
                },
                new Student()
                {
                    Id=1,
                    Name="大海",
                    ClassId=2,
                    Age=30
                },
                 new Student()
                {
                    Id=3,
                    Name="yoyo",
                    ClassId=3,
                    Age=30
                },
                  new Student()
                {
                    Id=4,
                    Name="unknown",
                    ClassId=4,
                    Age=30
                }
            };
            #endregion
            return studentList;
        }
        #endregion



        //声明委托
        public delegate bool ThanDelegate(Student student);
        
        private bool Than(Student student)
        {
            return student.Age > 25;
        }
        private bool LengthThan(Student student)
        {
            return student.Name.Length > 2;
        }
        private bool AllThan(Student student)
        {
            return student.Name.Length > 2 && student.Age > 25 && student.ClassId == 2;
        }


        public void Show()
        {

            List studentList = this.GetStudentList();
            {
                //this.GetList(studentList, 1);
                //调用委托
                ThanDelegate method = new ThanDelegate(this.Than);
                List result = this.GetListDelegate(studentList, method);
                Console.WriteLine($"结果一共有{result.Count()}个");
            }

            {
                //this.GetList(studentList, 2);
                ThanDelegate method = new ThanDelegate(this.LengthThan);
                List result = this.GetListDelegate(studentList, method);
                Console.WriteLine($"结果一共有{result.Count()}个");
            }

            {
                //this.GetList(studentList, 3);
                ThanDelegate method = new ThanDelegate(this.AllThan);
                List result = this.GetListDelegate(studentList, method);
                Console.WriteLine($"结果一共有{result.Count()}个");
            }
        }


        /// 
        /// 判断逻辑传递进来+实现共用逻辑
        /// 委托解耦,减少重复代码
        /// 
        /// 
        /// 
        /// 
        private List GetListDelegate(List source, ThanDelegate method)
        {
            List result = new List();
            foreach (Student student in source)
            {
                if (method.Invoke(student))
                {
                    result.Add(student);
                }
            }
            return result;
        }
    }
}

委托实现每个函数添加try catch

        public static void SafeInvoke(Action act)
        {
            try
            {
                act.Invoke();
            }
            catch (Exception ex)//按异常类型区分处理
            {
                Console.WriteLine(ex.Message);
            }
        }

调用有返回值无参数委托

public delegate int WithReturnNoPara();        
public void Show()
        {
            //调用委托
            WithReturnNoPara method = new WithReturnNoPara(this.GetSomething);
            int iResult = method.Invoke();
            //异步调用委托
    //var result=method.BeginInvoke(null, null);
    //method.EndInvoke(result);
        }
        private int GetSomething()
        {
            return 1;
        }


                {
                    NoReturnNoPara method = new NoReturnNoPara(DoNothingStatic);
                }
                {
                    NoReturnNoPara method = new NoReturnNoPara(Student.StudyAdvanced);
                }
                {
                    NoReturnNoPara method = new NoReturnNoPara(new Student().Study);

多播委托

                //多播委托:一个变量保存多个方法,可以增减;invoke的时候可以按顺序执行
                //+= 为委托实例按顺序增加方法,形成方法链,Invoke时,按顺序依次执行
                Student studentNew = new Student();

                NoReturnNoPara method = new NoReturnNoPara(this.DoNothing);
                method += new NoReturnNoPara(this.DoNothing);
                method += new NoReturnNoPara(DoNothingStatic);
                method += new NoReturnNoPara(Student.StudyAdvanced);
                method += new NoReturnNoPara(new Student().Study);//不是同一个实例,所以是不同的方法
                method += new NoReturnNoPara(studentNew.Study);
                method.Invoke();

                //method.BeginInvoke(null, null);//多播委托是不能异步的
                foreach (NoReturnNoPara item in method.GetInvocationList())
                {
                    item.Invoke();
                    //item.BeginInvoke(null, null);
                }
                //-= 为委托实例移除方法,从方法链的尾部开始匹配,遇到第一个完全吻合的,移除且只移除一个,没有也不异常
                method -= new NoReturnNoPara(this.DoNothing);
                method -= new NoReturnNoPara(DoNothingStatic);
                method -= new NoReturnNoPara(Student.StudyAdvanced);
                method -= new NoReturnNoPara(new Student().Study);
                method -= new NoReturnNoPara(studentNew.Study);
                method.Invoke();
            }
            {
                WithReturnNoPara method = new WithReturnNoPara(this.GetSomething);
                method += new WithReturnNoPara(this.GetSomething2);
                method += new WithReturnNoPara(this.GetSomething3);
                int iResult = method.Invoke();//多播委托带返回值,结果以最后的为准
            }
 public void Miao()
        {
            new Mouse().Run();
            new Baby().Cry();
            new Mother().Wispher();
            //new Brother().Turn();
            new Father().Roar();
            new Neighbor().Awake();
            new Stealer().Hide();
            new Dog().Wang();
        }

        //猫 叫一声   触发一系列后续动作  
        //多了个 指定动作  正是这个不稳定   封装出去   甩锅
 public delegate void MiaoDelegate();
 
 
 
 
         public MiaoDelegate MiaoDelegateHandler;
        public void MiaoNew()
        {
            Console.WriteLine("{0} MiaoNew", this.GetType().Name);
            if (this.MiaoDelegateHandler != null)
            {
                this.MiaoDelegateHandler.Invoke();
            }
        }

main函数

                       Cat cat = new Cat();
                        cat.MiaoDelegateHandler += new MiaoDelegate(new Mouse().Run);
                        cat.MiaoDelegateHandler += new MiaoDelegate(new Baby().Cry);
                        cat.MiaoDelegateHandler += new MiaoDelegate(new Mother().Wispher);
                        cat.MiaoDelegateHandler += new MiaoDelegate(new Brother().Turn);
                        cat.MiaoDelegateHandler += new MiaoDelegate(new Father().Roar);
                        cat.MiaoDelegateHandler += new MiaoDelegate(new Neighbor().Awake);
                        cat.MiaoDelegateHandler += new MiaoDelegate(new Stealer().Hide);
                        cat.MiaoDelegateHandler += new MiaoDelegate(new Dog().Wang);
                        cat.MiaoNew();
                        Console.WriteLine("***************************");

委托与事件的区别联系


        //事件:是带event关键字的委托的实例,event可以限制变量被外部调用/直接赋值
        //             cat.MiaoDelegateHandler.Invoke();
        //             cat.MiaoDelegateHandler = null;
        //委托和事件的区别与联系?
        //委托是一个类型,比如Student
        //事件是委托类型的一个实例,比如 果然
        public event MiaoDelegate MiaoDelegateHandlerEvent;
        public void MiaoNewEvent()
        {
            Console.WriteLine("{0} MiaoNewEvent", this.GetType().Name);
            if (this.MiaoDelegateHandlerEvent != null)
            {
                this.MiaoDelegateHandlerEvent.Invoke();
            }
        }

        //观察者模式

    }

    public class ChildClass : Cat
    {
        public void Show()
        {
            this.MiaoDelegateHandlerEvent += null;
            //if (this.MiaoDelegateHandlerEvent != null)//子类也不能调用
            //{
            //    this.MiaoDelegateHandlerEvent.Invoke();
            //}
        }

    }

Main

{
                        Cat cat = new Cat();
                        cat.MiaoDelegateHandlerEvent += new MiaoDelegate(new Mouse().Run);
                        cat.MiaoDelegateHandlerEvent += new MiaoDelegate(new Baby().Cry);
                        //cat.MiaoDelegateHandlerEvent.Invoke();
                        //cat.MiaoDelegateHandlerEvent = null;

                        cat.MiaoDelegateHandlerEvent += new MiaoDelegate(new Mother().Wispher);
                        cat.MiaoDelegateHandlerEvent += new MiaoDelegate(new Brother().Turn);
                        cat.MiaoDelegateHandlerEvent += new MiaoDelegate(new Father().Roar);
                        cat.MiaoDelegateHandlerEvent += new MiaoDelegate(new Neighbor().Awake);
                        cat.MiaoDelegateHandlerEvent += new MiaoDelegate(new Stealer().Hide);
                        cat.MiaoDelegateHandlerEvent += new MiaoDelegate(new Dog().Wang);
                        cat.MiaoNewEvent();
                        Console.WriteLine("***************************");
                    }
Linq表达式

匿名方法

 int k = 1;
//1.0  1.1
                NoReturnNoPara method = new NoReturnNoPara(this.DoNothing);
             //2.0 匿名方法 
                NoReturnNoPara method = new NoReturnNoPara(delegate ()
                {
                    Console.WriteLine(k);//能直接用到这里的变量
                Console.WriteLine("This is DoNothing1");
                });
                //3.0 lambda:左边是参数列表 goes to  右边是方法体   本质就是一个方法
                NoReturnNoPara method = new NoReturnNoPara(() =>//goes to
                {
                    Console.WriteLine("This is DoNothing2");
                });
            {
                NoReturnWithPara method = new NoReturnWithPara((int x, int y) => { Console.WriteLine("This is DoNothing3"); });
            }
            {//可以省略掉参数类型  自动推算的
                NoReturnWithPara method = new NoReturnWithPara((x, y) => { Console.WriteLine("This is DoNothing4"); });
            }
            {//方法体只有一行,可以去掉大括号和分号
                NoReturnWithPara method = new NoReturnWithPara((x, y) => Console.WriteLine("This is DoNothing5"));
            }
     //可以省略  编译器推算的
                NoReturnWithPara method = (x, y) => Console.WriteLine("This is DoNothing6");
          //    //匿名类 3.0
                //    object model = new//3.0
                //    {
                //        Id = 2,
                //        Name = "undefined",
                //        Age = 25,
                //        ClassId = 2
                //    };
                //    //Console.WriteLine(model.Id);//object 编译器不允许

//想使用
                //dynamic dModel = new//4.0
                //{
                //    Id = 2,
                //    Name = "undefined",
                //    Age = 25,
                //    ClassId = 2
                //};

      //    var varModel = new//3.0  编译后是有一个真实的类
                //    {
                //        Id = 2,
                //        Name = "undefined",
                //        Age = 25,
                //        ClassId = 2
                //    };
                //    Console.WriteLine(varModel.Id);
                //    //varModel.Id = 123;//只能get 没有set
                //    //反射可以找到

扩展方法,不能、不想修改类 直接调用即可

        public static void Sing(this Student student)
        {
            Console.WriteLine($"{student.Name} Sing a Song");
        }
        public static List ElevenWhere(this List source, Func func)
        {
            var list = new List();
            foreach (var item in source)
            {
                if (func.Invoke(item))
                {
                    list.Add(item);
                }
            }
            return list;

生成器

  public static IEnumerable ElevenWhere(this IEnumerable source, Func func)
            {
                if (source == null)
                {
                    throw new Exception("source is null");
                }
                if (func == null)
                {
                    throw new Exception("func is null");
                }

                foreach (var item in source)
                {
                    if (func.Invoke(item))
                    {
                        yield return item;
                    }
                }
            }

linq To Object

                    var linq = list
                        .Where(s =>
                    {
                        Console.WriteLine("检查数据是否满足条件");
                        Thread.Sleep(100);
                        return s.Age < 30;
                    })
                    //.Select(s => s.Name.Length);
                    .Select(s => new
                    {
                        Id = s.Id,
                        Name = s.Name,
                        Length = s.Name.Length
                    });






            {
                Console.WriteLine("********************");
                var list = studentList.Where(s => s.Age < 30)
                                     .Select(s => new
                                     {
                                         IdName = s.Id + s.Name,
                                         ClassName = s.ClassId == 2 ? "高级班" : "其他班"
                                     });
                foreach (var item in list)
                {
                    Console.WriteLine("Name={0}  Age={1}", item.ClassName, item.IdName);
                }
            }





            {
                Console.WriteLine("********************");
                var list = from s in studentList
                           where s.Age < 30
                           select new
                           {
                               IdName = s.Id + s.Name,
                               ClassName = s.ClassId == 2 ? "高级班" : "其他班"
                           };

                foreach (var item in list)
                {
                    Console.WriteLine("Name={0}  Age={1}", item.ClassName, item.IdName);
                }
            }









{
                Console.WriteLine("********************");
                var list = studentList.Where(s => s.Age < 30)//条件过滤
                                     .Select(s => new//投影
                                     {
                                         Id = s.Id,
                                         ClassId = s.ClassId,
                                         IdName = s.Id + s.Name,
                                         ClassName = s.ClassId == 2 ? "高级班" : "其他班"
                                     })
                                     .OrderBy(s => s.Id)//排序

                                     .OrderByDescending(s => s.ClassId)//倒排
                                     .Skip(2)//跳过几条
                                     .Take(3)//获取几条
                                     ;
                foreach (var item in list)
                {
                    Console.WriteLine($"Name={item.ClassName}  Age={item.IdName}");
                }
            }



            {//group by
                Console.WriteLine("********************");
                var list = from s in studentList
                           where s.Age < 30
                           group s by s.ClassId into sg
                           select new
                           {
                               key = sg.Key,
                               maxAge = sg.Max(t => t.Age)
                           };
                foreach (var item in list)
                {
                    Console.WriteLine($"key={item.key}  maxAge={item.maxAge}");
                }
                //group by new {s.ClassId,s.Age}
                //group by new {A=s.ClassId>1}
            }





            {
                Console.WriteLine("********************");
                var list = studentList.GroupBy(s => s.ClassId).Select(sg => new
                {
                    key = sg.Key,
                    maxAge = sg.Max(t => t.Age)
                });
                foreach (var item in list)
                {
                    Console.WriteLine($"key={item.key}  maxAge={item.maxAge}");
                }
            }



//多表操作

List classList = new List()
                {
                    new Class()
                    {
                        Id=1,
                        ClassName="初级班"
                    },
                    new Class()
                    {
                        Id=2,
                        ClassName="高级班"
                    },
                    new Class()
                    {
                        Id=3,
                        ClassName="微信小程序"
                    },
                };
            {
                var list = from s in studentList
                           join c in classList on s.ClassId equals c.Id
                           select new
                           {
                               Name = s.Name,
                               CalssName = c.ClassName
                           };
                foreach (var item in list)
                {
                    Console.WriteLine($"Name={item.Name},CalssName={item.CalssName}");
                }
            }









 {
                var list = studentList.Join(classList, s => s.ClassId, c => c.Id, (s, c) => new
                {
                    Name = s.Name,
                    CalssName = c.ClassName
                });
                foreach (var item in list)
                {
                    Console.WriteLine($"Name={item.Name},CalssName={item.CalssName}");
                }
            }



 {//左连接
                var list = from s in studentList
                           join c in classList on s.ClassId equals c.Id
                           into scList
                           from sc in scList.DefaultIfEmpty()//
                           select new
                           {
                               Name = s.Name,
                               CalssName = sc == null ? "无班级" : sc.ClassName//c变sc,为空则用
                           };
                foreach (var item in list)
                {
                    Console.WriteLine($"Name={item.Name},CalssName={item.CalssName}");
                }
                Console.WriteLine(list.Count());
            }
            {
                var list = studentList.Join(classList, s => s.ClassId, c => c.Id, (s, c) => new
                {
                    Name = s.Name,
                    CalssName = c.ClassName
                }).DefaultIfEmpty();//为空就没有了
                foreach (var item in list)
                {
                    Console.WriteLine($"Name={item.Name},CalssName={item.CalssName}");
                }
                Console.WriteLine(list.Count());
            }

public int Id=>3;
public void ShowLabda()=> Console.WriteLine("123");

Func、Action

            //Action 0到16个参数的 没有返回值  泛型委托
            Action action1 = () => { };
            Action action2 = i => Console.WriteLine(i);
            Action action17 = null;

            //Func   0到16个参数的 带返回值  泛型委托
            Func func1 = () => 1;
            Func func2 = i => i.ToString();
            Func func17 = null;

            this.DoNothing(action1);

            //NoReturnNoPara method = () => { };
            //this.DoNothing(method);
            //因为NoReturnNoPara和Action不是同一个类型
            //Student Teacher   大家属性都差不多,但是实例之间是不能替换的,因为我们没啥关系
            //很多委托长得一样,参数列表 返回值类型都一样,但是不能通用
            //在不同的框架组件定义各种各样的相同委托,就是浪费   比如ThreadStart委托
            //所以为了统一,就全部使用标准的Action  Func

        public delegate void NoReturnNoPara();

        private void DoNothing(Action act)
        {
            act.Invoke();
        }

linq To Sql 表达式目录树

      
Func func = (m, n) => m * n + 2;
                
                Expression> exp = (m, n) => m * n + 2;//lambda表达式声明表达式目录树
                                                                          //Expression> exp1 = (m, n) =>//只能一行 不能有大括号
                                                                          //    {
                                                                          //        return m * n + 2;
                                                                          //    };
                                                                          //Queryable    //a=>a.Id>3

                //表达式目录树:语法树,或者说是一种数据结构;可以被我们解析
                int iResult1 = func.Invoke(12, 23);
                int iResult2 = exp.Compile().Invoke(12, 23);//可以转换过去

//自己拼装表达树目录树,本质上是二叉树进行拆分计算

                ParameterExpression paraLeft = Expression.Parameter(typeof(int), "a");//左边
                ParameterExpression paraRight = Expression.Parameter(typeof(int), "b");//右边
                BinaryExpression binaryLeft = Expression.Multiply(paraLeft, paraRight);//a*b
                ConstantExpression conRight = Expression.Constant(2, typeof(int));//右边常量
                BinaryExpression binaryBody = Expression.Add(binaryLeft, conRight);//a*b+2

                Expression> lambda =
                    Expression.Lambda>(binaryBody, paraLeft, paraRight);
                Func func = lambda.Compile();//Expression Compile成委托
                int result = func(3, 4);

应用

                //以前根据用户输入拼装条件
                string sql = "SELECT * FROM USER WHERE 1=1";
                string name = "Eleven";//用户选择条件
                if (string.IsNullOrWhiteSpace(name))
                {
                    sql += $" and name like '%{name}%'";//应该参数化
                }



    //现在entity framework查询的时候,需要一个表达式目录树
                IQueryable list = null;
                //都不过滤 1
                if (true)//只过滤A 2
                {
                    Expression> exp1 = x => x.Id > 1;
                }
                if (true)//只过滤B 3
                {
                    Expression> exp2 = x => x.Age > 10;
                }

                //都过滤 4
                Expression> exp3 = x => x.Id > 1 && x.Age > 10;
                //2个条件  4种可能  排列组合
                //3个条件  2的3次方
                People people = new People()
                {
                    Id = 11,
                    Name = "Eleven",
                    Age = 31
                };
                PeopleCopy peopleCopy = new PeopleCopy()
                {
                    Id = people.Id,
                    Name = people.Name,
                    Age = people.Age
                };
                //硬编码 是不是写死了  只能为这两个类型服务   性能是最好的

可以用反射、序列化器(转JSON)
                    {
                    //反射 不同类型都能实现     
                    var result = ReflectionMapper.Trans(people);
                }
                {
                    //序列化器  不同类型都能实现
                    var result = SerializeMapper.Trans(people);
                }
    
    反射
    
    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExpressionDemo.MappingExtend
{
    public class ReflectionMapper
    {
        /// 
        /// 反射
        /// 
        /// 
        /// 
        /// 
        /// 
        public static TOut Trans(TIn tIn)
        {
            TOut tOut = Activator.CreateInstance();
            foreach (var itemOut in tOut.GetType().GetProperties())
            {
                var propIn = tIn.GetType().GetProperty(itemOut.Name);
                itemOut.SetValue(tOut, propIn.GetValue(tIn));
            }
            foreach (var itemOut in tOut.GetType().GetFields())
            {
                var fieldIn = tIn.GetType().GetField(itemOut.Name);
                itemOut.SetValue(tOut, fieldIn.GetValue(tIn));
            }
            return tOut;
        }
    }
}

序列化器
    
    using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExpressionDemo.MappingExtend
{
    /// 
    /// 使用第三方序列化反序列化工具
    /// 
    /// 还有automapper
    /// 
    public class SerializeMapper
    {
        /// 
        /// 序列化反序列化方式
        /// 
        /// 
        /// 
        public static TOut Trans(TIn tIn)
        {
            return JsonConvert.DeserializeObject(JsonConvert.SerializeObject(tIn));
        }
    }
}
3.用表达树目录树

你可能感兴趣的:(C#,c#,linq,microsoft)