扩展方法

利用扩展方法,实现参数验证。扩展方法三要素:

  1. 静态类
  2. 静态方法
  3. this关键字
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace 扩展方法
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             string name = Console.ReadLine();
14             name.Required();
15             Console.WriteLine("你好," + name);
16             Console.ReadKey();
17         }
18     }
19 
20     public static class Validate
21     {
22         public static void Required(this string data)
23         {
24             if (string.IsNullOrEmpty(data))
25             {
26                 //Console.WriteLine("姓名不能为空");
27                 throw new ArgumentException("参数不能为空。");                
28             }
29         }
30     }
31 }

 

posted @ 2014-06-09 21:56  David Huang  阅读(193)  评论(0编辑  收藏  举报