码迷,mamicode.com
首页 > Windows程序 > 详细

C#心得与经验(三)Regex,Exception,Delegate & Events

时间:2015-04-26 22:35:43      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:

一、Regular Expression

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

namespace RegexTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string string1 = "This is a test string";
            Regex theReg = new Regex(@"(\S+)\s");
            MatchCollection theMatches = theReg.Matches(string1);
            foreach (Match theMatch in theMatches){
                Console.WriteLine("theMatch.Length: {0}", theMatch.Length);
                if (theMatch.Length != 0)
                    Console.WriteLine("theMatch: {0}", theMatch.ToString());
            }
        }
    }
}

使用正则表达式来进行模式匹配,例中查找(\S+)\s即一个单词,使用@防止转译。

注意using System.Text.RegularExpressions;

Match()返回一个对象,Matches返回所有符合对象。

 

  .       任意单个字符char
 *       大于等于0个任意字符
 [a-f]  a-f间任意单个字符
 ^a     任意a开始的字符串
 z$      任意z结尾的字符串

 

二、Exception

使用try或者throw抛出异常 catch处理异常,有些异常可以什么也不做,类似EndOfStreamException。异常并不是漏洞或错误,异常的处理很重要,而且异常很影响程序的性能。

try {double a = 5;   double b = 0; DoDivide(a, b);}

catch (System.DivideByZeroException)

{…}

catch (System.ArithmeticException)

{…}

catch (Exception e)

{…}

public double DoDivide(double a, double  b)

{

   if (b == 0){throw new System.DivideByZeroException();}

   if (a == 0){throw new System.ArithmeticException();}

   return a / b;

}

finally

{

   …//无论异常是否发生,这里的代码都会被执行

}

 按照顺序catch并执行相应动作,finally内的语句始终执行。

 

三、Delegates & Events

 

委托类似之前学的指针,可以将方法封装方便调用。

delegate int Demo( int a, int b );

Demo test = new Demo(Class1.function());

test(1,2);

匿名:

Demo test = delegate(int a , int b){return (a == b);};

 

C#心得与经验(三)Regex,Exception,Delegate & Events

标签:

原文地址:http://www.cnblogs.com/funcode/p/4458388.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!