C#基础知识(六)

来源:互联网 发布:淘宝转化率0.05算正常 编辑:程序博客网 时间:2024/04/28 04:08

l      异常与异常处理

l     可以为null的类型和运算符“??”

l     类的多态性

l     字符串转换成datetime类型

l     集合使用和字符串练习

l     计时方法

1.异常与异常处理

之前学习过trycatch语句,用于捕获错误异常。而为了进一步研究和处理错误,可以在该语句上添加一个Exception类的实例。

例如:try

           {  

                        Console.Write("输入为:");      

               int i =Convert.ToInt32(Console.ReadLine());

           }

           catch(Exception ex)

           {

               Console.WriteLine("错误类型为:"+ex.Message);

           }

           Console.ReadKey();

 

如上,生成了一个对象ex,该对象的Message属性可以根据引发异常的不同错误输出不同的错误类型以解释产生错误的原因。而该对象的其他属性也可以对引发异常的错误做不同捕获处理。如下图:

Stack Trace属性可以用于查找错误发生位置。如下:

thrownewException();可用于添加自设异常。如下:

           try

           {

               Console.Write("输入为:");

             string ss = GetAgeDesc(int.Parse(Console.ReadLine()));

           }

           catch(Exception ex)                      //生成ex对象

           {

               Console.WriteLine("错误类型为:"+ex.Message);  //调用属性

           }

           Console.ReadKey();

       }                          //主方法大括号

       staticstring GetAgeDesc(int age)

       {

           if (age < 0)

           {

               thrownew Exception("年龄不能小于零");        //自设错误类型

           }

           elseif (age < 100)

           {

               return"正常年龄";

           }

           else

           {

               thrownew Exception("输入不正确");

           }

       

           

       }

 

2.可以为null的类型与运算符“??”

  可以为null的类型范围为其基础值类型正常范围内的值再加上一个null值(即未定义),引用类型stringobject可以直接声明赋null值,而值类型则需要转换成对应的可以为null的类型。

语法: T                    T表示值类型

例如:

           int? x =null ;          

           Console.WriteLine(x);

什么都不会输出。

           int? x = 4 ;          

           Console.WriteLine(x);

输出4.

运算符“??”

   该运算符用于在运算类型为可以为null的类型时用于分配值。如果该运算符左边的操作数非null,该运算符将返回左操作数,否则返回右操作数。

例如:

 

           int? x =null ;

           int y = x?? -1;

           Console.WriteLine(y);                //输出-1.

           int? x =null ;

           int y = (x??2) -1;

           Console.WriteLine(y);               //输出1,注意必须加括号

           int? x = 4 ;

           int y = x??6 -1;

           Console.WriteLine(y);              //输出4,说明??与=是同一级别运算符

           int? x = 4 ;

           int y = (x??6) -1;

           Console.WriteLine(y);              //输出3,只有加上括号,才会提升优先级

3.类的多态性    

  通过继承,类可以用作多种类型,即可以作为其本身的类型,也可以作为其他类的基类类型,还可以在实现接口时用作接口类型。一个类要在继承另一个类的同时实现接口,需要把基类写在前面,之后再写接口。   

    实现接口类型:

 classProgram

   {

       staticvoid Main(string[] args)

       {                       

           B b =newB();

           b.Get();

           b.Sub();         

           C c =newC();

           (cas ISub).Sub();

           D d =newD();

           d.Sup();

           (das ISup).Sub();

           Console.ReadKey();

       }

   }

   //ISub接口

   interfaceISub

   {

       void Sub();

   }

   //ISup接口

   interfaceISup

   {

       void Sup();

       void Sub();

   }

   //A

   classA

   {

       publicvoid Get()

       {

           Console.WriteLine("doing");

       }

   }

   //B,继承自A,实现ISub接口

   classB :A, ISub

   {

       //隐式实现接口

       publicvoid Sub()

       {

           Console.WriteLine("下标1");

       }       

   }

   //C,显式实现ISub接口

   classC:ISub

   {

       //显式实现接口

       voidISub.Sub()

       {

           Console.WriteLine("下标1");

       }

   }

   //D,实现ISup接口

   classD:ISup

   {

       //显式实现

       voidISup.Sub()

       {

           Console.WriteLine("下标2");

       }      

      publicvoid Sup()

       {

           Console.WriteLine("上标");

       }     

   }

一般我们都是隐式实现接口,只有在签名可能会出现重复的地方,才会显示实现,显示实现接口不需要加修饰词,但要通过接口调用方法。

New            子类成员与父类成员有相同名称签名等,可用new修饰子类成员来隐藏基类成员。

Virtual   override   前者修饰基类为虚拟成员,后者修饰子类中重写继承来的虚拟成员。虚方法要有方法体。

Abstract  override  前者修饰基类为抽象成员,子类继承后必须实现父类的抽象成员,用override修饰,抽象方法没有方法体。抽象方法必须包含在抽象类中。

4.字符串类型转换成datetime类型

  对于特殊格式的字符串,可以调用静态方法DateTime.ParseExact来转换成datetime类型。例如:

           string str ="20121210121222";

           DateTime date;

           date =DateTime.ParseExact(str, "yyyyMMddHHmmss", null);

           Console.WriteLine(date);

           

  如果不确定字符串格式,则可以通过尝试转换来转成datetime类型。

   string str ="2012.12.10 12:12:22"; 

           DateTime date;

           if (DateTime.TryParse(str,out date))

           {

               Console.WriteLine(date);

           }

           else

           {

               Console.WriteLine("转换失败");

           }

5.随机产生1-5454个不相同的数,存储到一个长度为54的数组中。(使用集合)

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

           Random r=newRandom ();

           while (list.Count < 54)

           {

               list.Add(r.Next(1,55));

               for (int i = 0; i < list.Count; i++)

               {

                   for (int j = i+1; j < list.Count; j++)

                   {

                       if (list[j] ==list[i])

                       {

                           list.RemoveAt(j);

                       }

                   }

               }

           }

           for (int i = 0; i < list.Count; i++)

           {

               Console.Write("{0}\t",list[i]);

           }

           Console.ReadKey();

6.怎么把一句话中的敏感词替换成数字个数???就是把这些敏感词找出来标序号???

           string[] strs = {"中国","共产党","毛泽东","政治"};

           string path=@"D:\html\检测.txt";

            //从文件中读取

           FileStream fs =new FileStream(path,FileMode.OpenOrCreate);

           StreamReader sr =new StreamReader(fs,Encoding.Default);

           string str = sr.ReadToEnd();

           int s=1;

           for (int i = 0; i < strs.Length; i++)

                         {

               if (str.Contains(strs[i]))

               {

                   str=str.Replace(strs[i], s.ToString());

                   s++;

               }

                         }

           Console.WriteLine(str);

         Console.ReadKey();

7.不精确测量时间的方法:

   1 Stopwatch watch =new Stopwatch();

           watch.Start();

           int[] nums = { 1, 32, 4, 656, 77, 89, 0, 0, -54, -2, 6, 5, 3, 3, 5, 7, 8, 1, 9, 6, 4535, 45, 3 };

           for (int i = 0; i < nums.Length; i++)

           {

               for (int j = 0; j < nums.Length - 1 - i; j++)

               {

                   int temp;

                   if (nums[j] > nums[j + 1])

                   {

                       temp = nums[j];

                       nums[j] = nums[j + 1];

                       nums[j + 1] = temp;

                   }

               }

           }

           for (int i = 0; i < nums.Length; i++)

           {

               Console.Write("{0}\t", nums[i]);

           }

           watch.Stop();           

           Console.WriteLine("耗时:{0}",watch.Elapsed.TotalMilliseconds);

2       DateTime beginTime =DateTime.Now;

           int[] nums = { 1, 32, 4, 656, 77, 89, 0, 0, -54, -2, 6, 5, 3, 3, 5, 7, 8, 1, 9, 6, 4535, 45, 3 };

           for (int i = 0; i < nums.Length; i++)

           {

               for (int j = 0; j < nums.Length - 1 - i; j++)

               {

                   int temp;

                   if (nums[j] > nums[j + 1])

                   {

                       temp = nums[j];

                       nums[j] = nums[j + 1];

                       nums[j + 1] = temp;

                   }

               }

           }

           for (int i = 0; i < nums.Length; i++)

           {

               Console.Write("{0}\t", nums[i]);

           }         

           TimeSpan ts=DateTime.Now.Subtract(beginTime);

           Console.WriteLine("耗时:{0}", ts.TotalMilliseconds);

原创粉丝点击