c#高级编程第七版笔记

来源:互联网 发布:键盘组合键软件 编辑:程序博客网 时间:2024/05/16 01:45

readonly: 这个字段只能在构造函数中初始化或者定义处初始化,别的地方都不可以初始化(红色的地方都是出错的)

还要注意的是:static变量只能在static方法中重新赋值,否则会错(在非静态函数中不能赋值静态字段)

    public class readonlyShow
    {
        public static readonly int a1=1;
        public readonly int a2;
        public readonlyShow()
        {
         // a1 = 2;
            a2 = 1;
        }
        public static readonlyShow()
        {
            a1 = 2;
        }
        public void errorSetValue
        {
          // a1=1;
        }
    }


VAR:  var关键字和new连用成员间用名值对方式赋值,逗号隔开

        public void varShow()
        {
            var b = new{ b1="1",b2="2",b3="3"};
            Console.Write(b.b1);
        }


ArraySegment: 顾名思义就是Array区块,数组的小抽屉,用于对该数组中元素的范围进行分隔

String[] myArr = { "Overred", "Medloy","Xiaoguai","Hare" };

ArraySegment<String> arrSeg = new ArraySegment<String>(myArr);

ArraySegment<String> myArrSegMid = new ArraySegment<String>(myArr, 1, 3);


Tuple: 元组可以通过item1,item2,.....进行访问

Tuple<int>,Tuple<int, int> 可以定义多个参数类型,最多八个,第八个可以声明为:Tuple<int,int>,定义写成 Tuple.Create<int,int>(1,1);(相当于迭代)

这样就能包含无限多个参数


  public static Tuple<int, int> Divide()
       {
           return Tuple.Create<int,int>(1,1);
       }

调用: var tuple = Divide();
           var item1 = tuple.Item1;
           var item2 = tuple.Item2;

??: 空合并运算符

var result= a??b;  如果aa不为空,则返回 a,如果为空,则返回b

 

Func :匿名函数:http://www.cnblogs.com/yyliuliang/archive/2009/04/01/1427589.html

匿名函数不会执行的很快,因为编译器仍然需要生成一个函数名,只是我们不知道这个名称

http://apps.hi.baidu.com/share/detail/33312383

           Func<string,string> anone= delegate(string para)
           {
                return "";
           };

 

       public static bool Divide(int a ,int b)
       {

           return true;
       }

       public void test(Func<int, int, bool> s) //前面几位是参数,后面一位 是函数的返回值
       {
        
       }

调用:

test(Divide);

多播委托: 不捕获的异常的话, 当一个委托异常或者失败后,后面的委托不会继续执行,想要=避免错误关联,需要使用:

           Delegate[] delegates = inttest.GetInvocationList();

 

Lambda表达式

("=>"左边是需要输入的参数,右边是赋予变量后的表达式方法。无参数直接用()表达),多参数用()表示,中间用 逗号 分隔

当表达式是一句话时候,不需要花括号

       Func< string> lambda =()=> { return ""; };
       Func<string, string> lamda1 = s => string.Format("hello {0}",s.ToString());
       Func<double, double, double> lamda2 = (x, y) => { return x * y; };//多参数
       Func<double,double,double> lamda3 =(x,y) => x*y ;
       Func<double, double, double> lamda4 = (double x, double y) => x * y;//也可以定义参数的类型
       Console.WriteLine(lamda3(2, 3)); //调用

 Event:事件

  public class customeEventArgs : EventArgs //自定义参数类型
   {
       public customeEventArgs()
       {
      
       }
   }
   public class EventTest
   {
       public event EventHandler<customeEventArgs> newEvent; //定义事件
       public EventTest() { }
       public void eventProcess() //被调方法,用于触发事件
       {
           if (newEvent != null)
           {
               newEvent(this, new customeEventArgs());
           }
      
       }
       public void eventFunction( object sender, customeEventArgs e)// 事件委托方法
       {
       
       }
  
   }
   public class EventReference
   {
       public EventReference()
       {
           EventTest test = new EventTest();
           test.newEvent += test.eventFunction;//绑定事件
           test.eventProcess();//调用事件
      
       }
   }

 说明:事件是一个特殊的委托,也是先声明事件,然后添加事件对应的被委托的方法,然后调用(触发事件 )

 

List:列表

           List<int> alist = new List<int>();
           alist.TrimExcess();//清除多余的空间(已经分配的内存)
           alist.ForEach(r => Console.WriteLine(“{0:C}”,r));//lambda表达式操作
                       alist.AddRange(new int[] { 1,2});//集中添加操作
                        alist.RemoveRange(1, 1);//集中删除操作

 

                        List<int> intlist =newList<int>();

           List<string> str = intlist.ConvertAll<string>(r => r.ToString());//ConvertAll:可以将通过lambda表达式,将一个对象转为另外一个对象也可以这样写初始构造方法:new 转化后的对象名(参数)

                       var listemp = intlist.Where<int>((r,index) => r=1 && index %2 !=0);//传递第二个参数index,作为索引操作

 

扫盲: str.ToLookup和GroupBy两者都有分组功能,但是groupby会延时。

延时操作: 

 

 Linq:

List<int> intlist =newList<int>();

var listemp = intlist.Where<int>((r,index) => r=1 && index %2 !=0);//传递第二个参数index,作为索引操作

varlistemp2 = ( from r in intlist
                          where r == 1
                          orderby r descending
                          select r ).ThenBy(r=> r).Take(10).Skip(10);

讲解: from in where select 是linq的基本语法,其中orderby 是排序,descending是降序属性,ThenBy是对查询的记录再次排序,Take是取得几个,Skip跳过记录数(相当于sql中的top)

    public class Person
   {
      public int id { get; set; }
      public string name { get; set; }
      public int classes { get; set; }
   }
   var personSearch = from p in persons
                              group p by p.classesinto g
                              orderby g.Key, g.Count() descending
                              where g.Count() > 2
                              select new
                              {
                                  country =g.Key,
                                  count =g.Count()
                              };

讲解: group 一条记录 by 该条记录中的某个字段(属性) into 保存到对象

             然后就是对对象进行操作,select new 是生成一个新的对象,相当于匿名对象

联合查询: join,Union All/Union/Intersect        http://blog.csdn.net/aladdinty/article/details/3599878

合并 : zip

var  listtemp3 =intlist.Zip(str,(first, second) => first + ":" + second);

说明: intlist对象1,str对象2,(first, second)对象1,2的变量,最终结果是我们lambda表达式里面的返回结果

分区: take(),skip()

聚合操作: Count(),Sum(),Min(),Max(),Average()

生成操作符:

varvalues =Enumerable.Range(1, 20);//1,2,3 ...20

var values2 =Enumerable.Repeat(1, 20);//1,1,1 ...1

 

并行LINQ

var  values =Enumerable.Range(1, 20)

var   value3 =values.AsParallel().Where(x=>x>1).Select(x=>x);//多线程

linq中,可以取消长线程的查询 WithCancellation()方法

 

dynamic 动态类型:作用很大,但是代价也很大,比一般的类型会耗时些(IL查看:编译器会做很多的补充工作)

var表示“变量的类型是在编译时决定的”,但是dynamic表示“变量的类型是在运行时决定的”。因此,dynamic与var具有截然不同的含义。

var让你在初始化变量时少输入一些字,编译器会根据右值来推断出变量的类型。dynamic更厉害,它告诉编译器,根本就别理究竟是啥类型,运行时再推断不迟。

var只能用于局部变量的定义,你不能把类的属性定义成 var,也不能把方法的返回值类型或者是参数类型定义成var。dynamic就没有这些局限了。

dynamic类型并没有跳过类型校验,只是延迟到了运行时。如果在运行时,检测到类型不兼容,照样会抛出异常。

 

reflect 反射

Type t = typeof(Person);

MethodInfo[] mo = t.GetMethods();

Assembly assembly1 = Assembly.Load("someassembly");//加载dll

Assembly assembly2 = Assembly.LoadFrom(@"c:\someassembly");//加载dll

Type[] types= assembly2.GetTypes();

 

线程

C#中使用线程的方法很多,使用委托的BeginInvokeEndInvoke方法就是其中之一。BeginInvoke方法可以使用线程异步地执行委托所指向的方法。然后通过EndInvoke方法获得方法的返回值(EndInvoke方法的返回值就是被调用方法的返回值),或是确定方法已经被成功调用。我们可以通过四种方法从EndInvoke方法来获得返回值。 

 使用Thread建立的线程默认情况下是前台线程,在进程中,只要有一个前台线程未退出,进程就不会终止。主线程就是一个前台线程。而后台线程不管线程是否结束,只要所有的前台线程都退出(包括正常退出和异常退出)后,进程就会自动终止。一般后台线程用于处理时间较短的任务

   要注意的是,必须在调用Start方法之前设置线程的类型,否则一但线程运行,将无法改变其类型。

    通过BeginXXX方法运行的线程都是后台线程

Thread.join方法只有在线程结束时才继续执行下面的语句

 

 

  public class ThreadTest
    {
        public ThreadTest()
        {
        }
        private static int newTast(int ms)
        {
            Console.WriteLine(" Task Begin ");
            Thread.Sleep(ms);
            Random random = new Random();
            int n = random.Next(10000);
            return n;
        }
        private delegate int NewTaskDelegate(int ms);
        void main(string[] args)
        {
            NewTaskDelegate task = newTast;

            //方法一,二公用
            IAsyncResult asyncresult = task.BeginInvoke(2000, null, null);

            //方法一
            while (!asyncresult.IsCompleted)
            {
                Thread.Sleep(1000);
            }
            //方法二
            while (!asyncresult.AsyncWaitHandle.WaitOne(100, false))
            {
               
            }

            int result = task.EndInvoke(asyncresult);
            Console.WriteLine(result);
            //方法三: 参数二:回调方法, 参数三: 回调方法的参数类型为: 被调用的委托
            task.BeginInvoke(2000,MethodComplete,task);


           //HttpWebRequest
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.cnblogs.com");
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
            sr.ReadToEnd();
            //delegate
            Thread thread1 = new Thread(delegate() { Console.WriteLine("hello world"); });
            Thread thread2 = new Thread(() => { Console.WriteLine("hello world"); });
            thread2.IsBackground = true;//是否后台执行

        }
        private void MethodComplete(IAsyncResult asyncresult)
        {
            if (asyncresult == null) return;
            string strresult = (asyncresult.AsyncState as NewTaskDelegate).EndInvoke(asyncresult).ToString();
            Console.WriteLine(strresult);
        }

    }

System.Threading.ThreadPool

 

MUTEX: 互斥,提供多个进程同步访问一个类,每次只能有一个线程获得互斥锁

            bool createdNew;
            Mutex mutex = new Mutex(false, "currentTest",out createdNew);
            if (!createdNew)
            {
                Console.Write("you can only start one instance");
            }

SemaphoreSlim:信号量,限定线程访问个数,阻塞剩下的线程,直至前面的线程解锁

var  semaphore =newSemaphoreSlim(1, 5);

线程里也有EVENTS,这个事件是线程间通信,和委托里的事件不同

ReaderWriterLockSlim: 读写锁

--------------------------------------------------------------------------------------------------------------

安全性:

windows权限

 文件访问权限

 

本地化

       区域性与线程有关

Thread.CurrentThread.CurrentCulture: 设置和格式化和排序选项一起使用的区域性,利用windows的”区域和语言“可以改变

Thread.CurrentThread.CurrentUICulture: 设置用户界面语言,依赖于操作系统测语言

            System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("es-ES");
            Thread.CurrentThread.CurrentCulture=ci;
            Thread.CurrentThread.CurrentUICulture = ci;

            acul.ToString("N", new CultureInfo("fr-FR"));

 Resource资源文件

 

WebClient ,WebRequest :网络请求,取得数据

        private void button1_Click(object sender, EventArgs e)
        {
            #region"WebClient"
            WebClient client = new WebClient();
            client.DownloadFile("http://www.cnblogs.com/twittersu/archive/2011/07/31/2123266.html","../../2123266.html");
           
            Stream strm= client.OpenRead("http://www.cnblogs.com/");
            StreamReader sr = new StreamReader(strm);
            string line=string.Empty;
            while ((line = sr.ReadLine()) != null)
            {
                listBox1.Items.Add(line);
            }
            sr.Close();
            #endregion

            #region"WebRequest"
            WebRequest request = WebRequest.Create("www.baidu.com");
            //身份验证
            //下面两行代码: 代理
            WebProxy wp = new WebProxy("192.168.1.100",true);
            wp.Credentials = new NetworkCredential("username", "password");
            //wp.Credentials = new NetworkCredential("username", "password","domain");

            NetworkCredential mycred = new NetworkCredential("username", "password");
           
            //不使用代理
            //request.Credentials = mycred;
            request.Proxy = wp;
            WebResponse response = request.GetResponse();

            Stream wstrm = response.GetResponseStream();
            StreamReader wsr = new StreamReader(wstrm);
            string wline = string.Empty;
            while ((wline = wsr.ReadLine()) != null)
            {
                listBox1.Items.Add(wline);
            }
            //异步加载
            //request.BeginGetResponse
            #endregion

            #region"操作浏览器"
            Process myprocess = new Process();
            myprocess.StartInfo.FileName = "iexplore.exe";
            myprocess.StartInfo.Arguments = "http://www.baidu.com";
            myprocess.Start();

            #endregion

            WebBrowser wb = new WebBrowser();
            wb.Navigate("www.baidu.com");
            wb.Print();

            //email
            SmtpClient sc = new SmtpClient();
            sc.Host = "mail.baidu.com";
            sc.Send("from@baidu.com", "send@baidu.com", "title", "cotent body");
            //MailMessage: 增加附件
            Attachment file = new Attachment("test.zip");
        }

 

操作文件: File,Directory

 

DirectoryInfo, FileInfo 它们都是有状态的,都需要实例化,在构造的时候读取对象的信息,在以后的使用后,不需要再次读取该对象信息了

File,Directory: 无状态的,每次使用的时候,都需要重新检查对象的详细内容

        public void filetest()
        {
            //FileInfo有状态
           
            FileInfo fileinfo = new FileInfo(@"c:\test.txt");
            if (fileinfo.Exists)
            {
                fileinfo.CopyTo(@"d:\Readme.text");
            }
            //File无状态
            File.Copy(@"c:\test.txt", @"d:\Readme.text");
            Path.Combine(@"c:", "Readme.text");
            //读取文件
            string textcontent = File.ReadAllText(@"d:\Readme.text",Encoding.ASCII);
            File.WriteAllText(@"d:\Readme.text", "hello");

            //stream
            FileStream fs = new FileStream(@"d:\Readme.text",FileMode.Create,FileAccess.ReadWrite,FileShare.None);
            fs.Close();
            //映射内存文件
            var mefile = MemoryMappedFile.CreateFromFile(@"d:\Readme.text");
            //驱动信息(C盘,D盘等   )
            DriveInfo[] di = DriveInfo.GetDrives();
        }

 

 

using

读写独立存储器

System.IO.IsolatedStorage: 存储应用程序状态和用户设置,可以看做虚拟磁盘

 

ADO.NET

 DataSet ds =DataSet.copy()拷贝框架,数据关系

 DataSet.clone() 只拷贝框架

DataSet dest = ds.GetChanges();得到修改过的行记录

原创粉丝点击