[Visual C#] 工厂类的实现

 1     /// <summary>
 2     /// 表示一组静态方法,这些方法用于创建SMSProviderFactory类的一个或多个实例
 3     /// </summary>
 4     public class SMSProviderFactories
 5     {
 6         /// <summary>
 7         /// 返回SMSProviderFactory的一个实例
 8         /// </summary>
 9         /// <param name="providerInvariantName">提供程序的固定名称</param>
10         /// <returns></returns>
11         public static SMSProviderFactory GetFactory(string providerInvariantName)
12         {
13             if (string.IsNullOrEmpty(providerInvariantName))
14             {
15                 throw new ArgumentNullException("providerInvariantName");
16             }
17             try
18             {
19                 Type type = Type.GetType(providerInvariantName);
20 
21                 if (type == null)
22                 {
23                     throw new Exception("指定的提供程序并未安装!");
24                 }
25 
26                 FieldInfo field = type.GetField("Instance", BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);
27 
28                 if ((field != null) && field.FieldType.IsSubclassOf(typeof(SMSProviderFactory)))
29                 {
30                     object obj = field.GetValue(null);
31 
32                     if (obj != null)
33                     {
34                         return (SMSProviderFactory)obj;
35                     }
36                 }
37             }
38             catch (Exception err)
39             {
40                 throw err;
41             }
42 
43             throw new Exception("提供程序丢失");
44         }
45     }
原文地址:https://www.cnblogs.com/briny/p/2637334.html