关于c#高级语法

第一章:c#委托

创建委托

 //创建一个委托 delegate
    public delegate void zj(string s);

创建委托类型对象把方法当作参数传进来

  • 委托的类型和参数必须和委托的方法的类型和参数一样的
static void Main(string[] args)
        {
            // 创建委托类型的对象 ,将方法名作为参数传递进来
            zj zj = new zj(Mf);
            zj.Invoke("张三");
            zj zj1 = maif;//简化方式
            zj1.Invoke("小沈");
             //多播委托
            zj += maif;
            //删除委托 : zj-=maif;
            zj("张三");
        }
        public static void maif(string s)
        {
            Console.WriteLine(s+"卖出一套房子");
        }
        public static void Mf(string s)
        {
            Console.WriteLine(s+"买了一套汤臣一品");
        }
  • 可以创建一个以委托为参数的方法

            public delegate void Act();
            public static void action(Act act)
            {
                act.Invoke();
            }
    

匿名类型

var a=new {
    id=511,
    Name="帅气",
    age=5
}
a.GetType();//获取类型
  • 委托匿名

        //声明一个委托类
        public delegate void other(int a, int b);    
    
        other other = delegate (int x, int y)
                  {
        Console.WriteLine("{2}+{1}={0}", x + y , x, y);
                  };
                other.Invoke(6, 7);
    

c#扩展方法

自定义内方法

 public static  class StringExd
    {
       public static int count(this string s)
        {
        return s.Split(new char[] { ' ','.',',','?'},StringSplitOptions.RemoveEmptyEntries).Count();
        }
    }
//运用
string s="hellow, how are you";
int cout=count(s);//解决的方法
console.writeLine(count)//有多少个单词

枚举类

   //1-100被3整除的数 ,yield关键字
// 不断返回
        public static IEnumerable<int> getlist()
        {
            for (int i = 1; i <= 100; i++)
            {
                if (i % 3 == 0)
                {
                    yield return i;
                }
            }
        }

lambda

  public delegate void weiT(int a, int b);

  weiT weiT = new weiT((int x,int y)=> {
                Console.WriteLine("{0}+{1}={2}",x,y,x+y);
            });
//两种采用 
new weiT((x, y)=> {
                Console.WriteLine("{0}+{1}={2}",x,y,x+y);
            })(8,9);
    //Action内置的委托方法《string》定义类型
       new Action<string>((s) =>
            {
                Console.WriteLine(s + "你吃了吗");
            })("小张");

匿名方法

  public delegate int weiT(int a, int b);


weiT wei=delegate (int x,int y){
    return x+y;
}
wei(5,6)

第二章:LINQ查询

   int[] nums = new int[7] {0,1,2,3,4,5,6 };
//num :自己定义的局部变量
            var result = from num in nums
                         where num % 2 == 0
                         select num;
            foreach (var item in result)
            {
                Console.WriteLine(item);
            }
//创建对象
    public string Name { get; set; }
    public string CategoryID { get; set; }
查询所有
      List<Products> pList = new List<Products>()
            {
                new Products{ Name="iphone11",CategoryID="手机"},
                new Products{ Name="华为Mate",CategoryID="手机"},
                new Products{ Name="小米电视",CategoryID="家电"},
                new Products{ Name="运动鞋",CategoryID="鞋子"}
            };
            var result = from n in pList select n;

            foreach (var item in result)
            {
                Console.WriteLine(item.CategoryID);
                Console.WriteLine(item.Name);
            }
//列子:假如要查询类别为鞋子的
    // var result = from n in pList 
      //            where n.CategoryID=="鞋子" 
        //          select n;

// 查询分组以 类型 :from n in pLisy group n by n.CategoryID;
/**
   foreach (var item in result)
            {

                Console.WriteLine(item.key);
            }
*/
    
 //查询每种产品的数量
            var results = from p in pList
                          group p by p.CategoryID into g
                          select new {g.Key,ProNums=g.Count() };//ProNums定义数量的名字(随意取)
            foreach (var item in results)
            {
                Console.WriteLine(item.Key);
                Console.WriteLine(item.ProNums);
            }
排序查询
  • //创建对象
      public string LastName { get; set; }
            public string TitleOfCourtesy { get; set; }
    
    List<Employees> eList = new List<Employees>()
            {
                new Employees{LastName="王二",TitleOfCourtesy="助理设计师"},
                new Employees{LastName="张三",TitleOfCourtesy="软件设计师"},
                new Employees{LastName="李四",TitleOfCourtesy="助理设计师"},
                new Employees{LastName="王五",TitleOfCourtesy="系统设计师"},
                new Employees{LastName="赵六",TitleOfCourtesy="系统分析师"}
            };
            var result = from p in eList
                         orderby p.TitleOfCourtesy //descending
                         select p;
//降序:descending
//第二种写法
//var results = from p in eList
            //              select new
            //              {
            //                  LastName = p.LastName,
            //                  Title =        p.TitleOfCourtesy
            //              } into e
            //              orderby e.Title
            //              select e;
            foreach (var item in result)
            {
                Console.WriteLine("{0},{1}",item.LastName,item.TitleOfCourtesy);
            }
列式编程查询
//查询里面有"a"   
string[] names = { "Toms", "jack", "Dick", "Harry", "Mary" };
            IEnumerable<string> res=
            names.Where(n => n.Contains('a'))
                .OrderBy(n => n.Length)
                .Select(n => n.ToUpper());
            foreach (var item in res)
            {
                Console.WriteLine(item);
            }
查询特有字段
  • 添加对象
List<Student> students = new List<Student>
            {
                new Student {First="Svetlana", Last="Omelchenko", ID=111, Scores= new List<int> {97, 92, 81, 60}},
                new Student {First="Claire", Last="ODonnell", ID=112, Scores= new List<int> {75, 84, 91, 39}},
                new Student {First="Sven", Last="Mortensen", ID=113, Scores= new List<int> {88, 94, 65, 91}},
                new Student {First="Cesar", Last="Garcia", ID=114, Scores= new List<int> {97, 89, 85, 82}},
                new Student {First="Debra", Last="Garcia", ID=115, Scores= new List<int> {35, 72, 91, 70}},
                new Student {First="Fadi", Last="Fakhouri", ID=116, Scores= new List<int> {99, 86, 90, 94}},
                new Student {First="Hanying", Last="Feng", ID=117, Scores= new List<int> {93, 92, 80, 87}},
                new Student {First="Hugo", Last="Garcia", ID=118, Scores= new List<int> {92, 90, 83, 78}},
                new Student {First="Lance", Last="Tucker", ID=119, Scores= new List<int> {68, 79, 88, 92}},
                new Student {First="Terry", Last="Adams", ID=120, Scores= new List<int> {99, 82, 81, 79}},
                new Student {First="Eugene", Last="Zabokritski", ID=121, Scores= new List<int> {96, 85, 91, 60}},
                new Student {First="Michael", Last="Tucker", ID=122, Scores= new List<int> {94, 92, 91, 91}}
            };
            

求平均值(查询特有的字段)

 //求平均值(查询特有的字段)
            var resus = students.Select(s => new
            {
                first = s.First,
                last = s.Last,
                score = s.Scores.Average()//平均方法
            });
            foreach (var item in resus)
            {
                Console.WriteLine("{0},{1},{2}",item.first,item.last,item.score);
            }
  • FirstOrDefault:返回第一个元素,没有则返回默认值

  • var s = students.FirstOrDefault();
    if(s!=null){
    console.writeLine("{0},{1}",s.First,s.Last)
    }
    LastOrDefault()//:返回最后一个元素,没有则返回默认值
     students.ElementAtOrDefault(5)//返回索引为5的,没有则返回默认值
    
数据转换操作
  • 转换集合:ToList()

  • //查出平均分>85的学生,并将结果转为List集合
    //students:上面的添加的对象
      List<Student> r = students.Where(c => c.Scores.Average() > 85).ToList();
    
    //假如List<student>换成ArrayList();
    //用Cast<Student>()强转换
    students.Cast<Student>()
    
  • 转换不满足的条件的过滤转换

  • var results=students.OfType<Student>(.where)//除了Student都会过滤掉
    

第三章:ORM数据框架技术

ORM增删改查操作

查询数据库里面的值,并且绑定表
  •  using (meixinEntities db=new meixinEntities())
        {
            var data = db.m_user.ToList();
                   this.GridView1.DataSource = data;
                   DataBind();
        }
    
添加数据库数据:Add
 m_user _User = new m_user();
  _User.email = "3024888569@qq.com";
 _User.pwd = "123456";
_User.logintime = DateTime.Now;
 db.m_user.Add(_User);//添加
 db.SaveChanges();//保存更改
Response.Write("成功");
删除对象,数据库
         int id=int.Parse(this.GridView1.Rows[e.RowIndex].Cells[0].Text);
            //m_user _User = new m_user();
            //_User.id =Convert.ToInt32(id);
      
            using (meixinEntities db=new meixinEntities())
            {
                var user = db.m_user.FirstOrDefault(n => n.id == id);//获取满足该条件的第一条数据
                db.m_user.Remove(user);
                db.SaveChanges();
             }
            NewMethod();//重新获取页面
修改数据:GridView1
  protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            this.GridView1.EditIndex = -1;
              NewMethod();//重新获取页面
        }

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            this.GridView1.EditIndex = e.NewEditIndex;
           NewMethod();//重新获取页面
        }

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            int id = Convert.ToInt32(this.GridView1.Rows[e.RowIndex].Cells[0].Text);
            using (meixinEntities db = new meixinEntities())
            {
              var user=  db.m_user.FirstOrDefault(n => n.id == id);
                user.pwd = ((TextBox)(this.GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text;
                user.email = ((TextBox)(this.GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text;
               user.logintime = Convert.ToDateTime(((TextBox)      (this.GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text);
                db.SaveChanges();//保存修改   
                }
            this.GridView1.EditIndex = -1;
              NewMethod();//重新获取页面
        }

ORM增删改查多表

绑定下拉菜单

第四章:利用EF进行sql执行

数据库方面

Database.ExecuteSqlCommand :增删改

   using(EFTestEntities db=new EFTestEntities())
            {
                string sql = $"create table Admin(id int primary key not null," +
                    "Account varchar(16)," +
                    "password varchar(20))";
                var result = db.Database.ExecuteSqlCommand(sql);
                Console.WriteLine(result);
            }

添加数据

string sql = "insert into Admin values" +
                    "(1,'张三','zm123')" +
                    ",(2,'李四','lmm123')";
                var result = db.Database.ExecuteSqlCommand(sql);
                Console.WriteLine(result);

修改数据 进行传参

  • @pwd1,@id1为参数占位符
 string sql = @"update Admin set password = @pwd1 where id = @id1";
                SqlParameter[] parm = new SqlParameter[]
                {
                  new SqlParameter("@pwd1","123456"),
                  new SqlParameter("@id1",1)

                };
                var res = db.Database.ExecuteSqlCommand(sql,parm);
                Console.WriteLine(res);

删除数据

  • string sql = "delete from Admin where id=2";
                   var result = db.Database.ExecuteSqlCommand(sql);
    

查询数据:SqlQuery

   string sql = "select * from Admin where id>=1 order by account desc";
                var data = db.Database.SqlQuery<Admin>(sql);

                foreach (var item in data)
                {
                    Console.WriteLine("{0},{1},{2}",item.id,item.password,item.Account);
                }

查询行数:int


                //string sql = "select * from Admin where id>=1 order by account desc";
                //var data = db.Database.SqlQuery<Admin>(sql);
                //int count = data.ToList().Count;
                //Console.WriteLine(count);
                //foreach (var item in data)
                //{
                //    Console.WriteLine("{0},{1},{2}",item.id,item.password,item.Account);
                //}
     
                string sql = "select count(*) from Admin ";
                var data = db.Database.SqlQuery<int>(sql);
                foreach (var item in data)
                {
                    Console.WriteLine("{0}",item);
                }

查询后进行更新

  string sql = "select * from Admin where id>=1 order by account desc";
                var data = db.Database.SqlQuery<Admin>(sql).FirstOrDefault();
                data.password = "123123";
                db.Entry<Admin>(data).State = System.Data.Entity.EntityState.Modified;//传递状态已经被修改
                db.SaveChanges();//保存修改

调用存储过程

  var admin = db.getAdmin(2).ToList().FirstOrDefault();
                Console.WriteLine("{0},{1},{2}",admin.id,admin.password,admin.Account);

调用增加数据的存储过程

  • 在数据模型中更新,添加了存储过程后才能调用
  • image-20220308112516169
  int num = db.getInsert(6, "yuanxiao", "131316");
                Console.WriteLine(num);//行数

code first模式

  • 先创建对象类

  • //用户类  
    class User	
        {
            public int Id { get; set; }
            public string Email { get; set; }
            public string pwd { get; set; }
            public Nullable<DateTime> LoginTime { get; set; }
            public virtual ICollection<order> Order { get; set; }
        }
    
    //创建订单对象
    class order
        {
            public int id { get; set; }
            public string phone { get; set; }
            public string address { get; set; }
            public string message { get; set; }
            public string status { get; set; }
            public Nullable<System.DateTime> orderTime { get; set; }
            public virtual User user { get; set; }
        }
    
    • 引入空的code first模型
    • 编写代码
    class MexinContext:DbContext
        {
            public MexinContext():base("name=Mexin")
            {
    
            }
           //这是先前创建的对象类,与之关联,返回DbSet
            public virtual DbSet<User> Users { get; set; }
        
                // virtual导航属性 默认会有延迟加载
            public virtual ICollection<order> Order { get; set; }
        }
    
    • 在app.config里面添加

    • <connectionStrings>
         <add name="Model1" connectionString="data source=(LocalDb)\MSSQLLocalDB;initial catalog=Task4._4.Model1;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
       	  <!--在这里面重复添加,name与之前的类:base("name=Mexin")一致
       	  把(LocalDb)\MSSQLLocalDB改成 .
       	  -->
       	  <add name="Meixin" connectionString="data source=.;initial catalog=Model1;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
       </connectionStrings>
       	<!--连接属性-->
      
      • 创建class InitDatabase

      • class InitDatabase:DropCreateDatabaseIfModelChanges<MexinContext>
           {
               protected override void Seed(MexinContext context)
               {
                   //base.Seed(context);
                   User user = new User()
                   {
                       Id = 2,
                       Email = "ym@163.com",
                       pwd = "123654",
                       LoginTime = DateTime.Now
                   };
                   context.Users.Add(user);
                   context.SaveChanges();
                   Console.WriteLine("挺好的");
               }
              
           }
        

延迟加载的启动和关闭

  db.Configuration.LazyLoadingEnabled = false;//关闭延迟加载,反则false

贪婪加载

var data = db.m_user.Include("m_order").FirstOrDefault(p => p.id == 1);

显示加载

   var data = db.m_user..FirstOrDefault(p => p.id == 1);
      db.Entry(data).Collection("m_order").Load();

第五章:理解.net运行机制

1.创建请求前后的方法

  • 创建类
 public class TextModule : IHttpModule
    {
        public void Dispose()
        {
            throw new NotImplementedException();
        }

        public void Init(HttpApplication context)
        {
            //handler处理请求前的执行方法begin
            context.BeginRequest += begin;
            //handler处理请求后的执行方法end
            context.EndRequest += end;
        }

        private void end(object sender, EventArgs e)
        {
            HttpApplication application = sender as HttpApplication;
            application.Response.Write("<p>module结束处理请求</p>");
        }

        private void begin(object sender, EventArgs e)
        {
            HttpApplication application = sender as HttpApplication;
            application.Response.Write("<p>module开始处理请求</p>");
        }
    }
  • 在配置web.config里面配置
	<system.webServer>
		<modules>
			<add name="test" type="demo5_.TextModule"/>
        //demo5_是路径
		</modules>
	</system.webServer>

2.盗链:

  • 因为盗链是一个不好的行为,我们就防止此事件发生

  • 创建Handler1.ashx:一般处理程序

  • public class Handler1 : IHttpHandler
       {
     
           public void ProcessRequest(HttpContext context)
           {
               //返回上一次访问的请求
               Uri lasturl= context.Request.UrlReferrer;
               //返回本次的请求地址
               Uri uri = context.Request.Url;
               if (lasturl.Host != uri.Host||lasturl.Port!=uri.Port)
               {
                   //如果两个不太一致,说明盗链
              string errulr=     context.Request.PhysicalApplicationPath + "Error/default.jpg";
                   context.Response.WriteFile(errulr);
                   //Error/default.jpg:是事先准备的被盗的图片
               }
               else
               {
                   string errulr1 = context.Request.PhysicalApplicationPath;
                   context.Response.WriteFile(errulr1);
               }
          }
      
           public bool IsReusable
           {
               get
               {
                   return false;
               }
           }
      }
    
    • 然后配置web.comfig

第六章:AjAX前后台交互

重写URL

  • 编写虚拟的地址

  •     <ul>
            <li>
                <a href="Goods_1.html">服装</a>
            </li>
             <li>
                <a href="Goods_2.html">商品</a>
            </li>
        </ul>
    
    • 编写获取接口的

    • public class RewriteModule : IHttpModule
       {
           public void Dispose()
           {
               throw new NotImplementedException();
           }
         
           public void Init(HttpApplication context)
           {
               context.BeginRequest += rewriteUrl;
         
           }
         
           private void rewriteUrl(object sender, EventArgs e)
           {
         
               //1.获取地址
                 HttpApplication application= sender as HttpApplication;
                  string res = application.Request.RawUrl;
               
               //2.为了安全,编写正则表达式、
               Regex regex = new Regex(@"\w+_\d+\.html");
               if (regex.IsMatch(res))
               {
                   int numline = res.LastIndexOf("_");
                   int dot = res.LastIndexOf(".");
                   //截取地址里面的id数字
                   string id = res.Substring(numline + 1, dot -numline- 1);
                   //重新组装地址
                   string reaurl = "~/GoodsList.aspx?id" + id;
                   application.Server.Transfer(reaurl);//Transfer:终止当前页的地址,传入一个新的地址,并且调转
               }
      
          }
      }
      
      - 配置文件
      
      - ```c#
        	<system.webServer>
        		<modules>
        			<add name="ets" type="Test6._1.RewriteModule"/>
        		</modules>
        	</system.webServer>
      
    - 在GoodsList.aspx里面写
    
    - ```c#
       protected void Page_Load(object sender, EventArgs e)
              {
                  Response.Write("id=" + Request["id"]);
              }
      ```
    

ajax: asp

function showHint(str)
{
    var xmlhttp;
    if (str.length==0)
    { 
        document.getElementById("txtHint").innerHTML="";
        return;
    }
    if (window.XMLHttpRequest)
    {
        // IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
        xmlhttp=new XMLHttpRequest();
    }
    else
    {
        // IE6, IE5 浏览器执行代码
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    //onreadystatechange是获取的xmlhttp的状态变化
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","地址"+str,true);
    xmlhttp.send();
}
  • 解析xml

  • xmlDoc=xmlhttp.responseXML;
    txt="";
    x=xmlDoc.getElementsByTagName("ARTIST");
    for (i=0;i<x.length;i++)
    {
        txt=txt + x[i].childNodes[0].nodeValue + "<br>";
    }
    document.getElementById("myDiv").innerHTML=txt;
    
posted @ 2023-01-14 16:06  只心  阅读(59)  评论(0)    收藏  举报