在泛型类和泛型方法中产生的一个问题是,在预先未知以下情况时,如何将默认值分配给参数化类型 T:  T 是引用类型还是值类型。 如果 T 为值类型,则它是数值还是结构。 给定参数化类型 T 的一个变量 t,只有当 T 为引用类型时,语句 t  =   null  才有效;只有当 T 为数值类型而不是结构时,语句 t  =   0  才能正常使用。解决方案是使用  default  关键字,此关键字对于引用类型会返回空,对于数值类型会返回零。对于结构,此关键字将返回初始化为零或空的每个结构成员,具体取决于这些结构是值类型还是引用类型。以下来自 GenericList < T >  类的示例显示了如何使用  default  关键字。 Demo: Class  class   =   new  Class(); public   void   get < T > (T  class ) {      class   =   default (T); }  result: class   = null ;  
1.泛型和泛型强制转换
 1 using  System;  2 using  System.Collections.Generic;  3 using  System.Text;  4  5 namespace  VS2005Demo2  6 {  7  8      C# 编译器只允许将泛型参数隐式强制转换到 Object 或约束指定的类型 #region   C# 编译器只允许将泛型参数隐式强制转换到 Object 或约束指定的类型  9      public   interface  ISomeInterface 10      { } 11      class  BaseClass 12      { } 13      class  MyClass < T >  where T : BaseClass, ISomeInterface 14      { 15          void  SomeMethod(T t) 16          { 17              ISomeInterface obj1 =  t; 18              BaseClass obj2 =  t; 19              object  obj3  =  t; 20          }21      }22      #endregion 23 24      编译器允许您将泛型参数显式强制转换到其他任何接口,但不能将其转换到类 #region  编译器允许您将泛型参数显式强制转换到其他任何接口,但不能将其转换到类 25      class  SomeClass 26      { } 27      // class MyClass1<T> 28      // { 29      //     void SomeMethod(T t) 30      //     { 31      //         ISomeInterface obj1 = (ISomeInterface)t;   // Compiles 32      //         SomeClass obj2 = (SomeClass)t;            // Does not compile 33      //     } 34      // } 35      #endregion 36 37 38      使用临时的 Object 变量,将泛型参数强制转换到其他任何类型 #region  使用临时的 Object 变量,将泛型参数强制转换到其他任何类型 39      class  MyClass2 < T > 40      { 41          void  SomeMethod(T t) 42          { 43              object  temp  =  t; 44              SomeClass obj =  (SomeClass)temp; 45          }46      }47      #endregion 48 49      使用is和as运算符 #region  使用is和as运算符 50      public   class  MyClass3 < T > 51      { 52          public   void  SomeMethod(T t) 53          { 54              if  (t  is   int )  { } 55              if  (t  is  LinkedList < int ,  string > )  { } 56              string  str  =  t  as   string ; 57              if  (str  !=   null )  { } 58              LinkedList< int ,  string >  list  =  t  as  LinkedList < int ,  string > ; 59              if  (list  !=   null )  { } 60          }61      }62      #endregion 63 64  }65  
2.继承和泛型
  1 using  System;   2 using  System.Collections.Generic;   3 using  System.Text;   4   5 namespace  VS2005Demo2   6 {   7      继承和泛型 #region  继承和泛型   8      public   class  BaseClass < T >   9      { }  10      public   class  SubClass : BaseClass < int >  11      { }  12  13  14      public   class  SubClass1 < R >  : BaseClass < R >  15      { }  16      #endregion  17  18      继承约束 #region  继承约束  19      public   class  BaseClass1 < T >  where T : ISomeInterface  20      { }  21      public   class  SubClass2 < T >  : BaseClass1 < T >  where T : ISomeInterface  22      { }  23  24      // 构造函数约束  25      public   class  BaseClass3 < T >  where T :  new ()  26      {  27          public  T SomeMethod()  28          {  29              return   new  T();  30          } 31      } 32      public   class  SubClass3 < T >  : BaseClass3 < T >  where T :  new ()  33      { }  34  35      #endregion  36  37      虚拟方法 #region  虚拟方法  38      public   class  BaseClass4 < T >  39      {  40          public   virtual  T SomeMethod()  41          {  42              return   default (T);  43          } 44      } 45      public   class  SubClass4 : BaseClass4 < int >  46      {  47          public   override   int  SomeMethod()  48          {  49              return   0 ;  50          } 51      } 52  53      public   class  SubClass5 < T >  : BaseClass4 < T >  54      {  55          public   override  T SomeMethod()  56          {  57              return   default (T);  58          } 59      } 60  61      #endregion  62  63      接口、抽象类继承 #region  接口、抽象类继承  64      public   interface  ISomeInterface6 < T >  65      {  66          T SomeMethod(T t); 67      } 68      public   abstract   class  BaseClass6 < T >  69      {  70          public   abstract  T SomeMethod(T t);  71      } 72      public   class  SubClass6 < T >  : BaseClass6 < T > ,ISomeInterface6 < T >  73      {  74          public   override  T SomeMethod(T t)  75          {  return   default (T); }  76      } 77      #endregion  78  79      泛型抽象方法和泛型接口 #region  泛型抽象方法和泛型接口  80      // public class Calculator<T>  81      // {  82      //     public T Add(T arg1, T arg2)  83      //     {  84      //         return arg1 + arg2; // Does not compile   85      //     }  86      //      // Rest of the methods   87      // }  88  89      public   abstract   class  BaseCalculator < T >  90      {  91          public   abstract  T Add(T arg1, T arg2);  92          // public abstract T Subtract(T arg1, T arg2);  93          // public abstract T Divide(T arg1, T arg2);  94          // public abstract T Multiply(T arg1, T arg2);  95     }  96      public   class  MyCalculator : BaseCalculator < int >  97      {  98          public   override   int  Add( int  arg1,  int  arg2)  99          { 100              return  arg1  +  arg2; 101          }102          // Rest of the methods  103     } 104 105      public   interface  ICalculator < T > 106      { 107          T Add(T arg1, T arg2);108          // Rest of the methods  109     } 110      public   class  MyCalculator1 : ICalculator < int > 111      { 112          public   int  Add( int  arg1,  int  arg2) 113          { 114              return  arg1  +  arg2; 115          }116          // Rest of the methods  117     } 118      #endregion 119 120  }121  
3.泛型方法
  1 using  System;   2 using  System.Collections.Generic;   3 using  System.Text;   4   5 namespace  VS2005Demo2   6 {   7   8      泛型方法 #region  泛型方法   9      public   class  MyClass  10      {  11          public   void  MyMethod < T > (T t)  12          { }  13      } 14  15      public   class  Class3  16      {  17          public   void  Test()  18          {  19              MyClass obj =   new  MyClass();  20              obj.MyMethod< int > ( 3 );  21  22              obj.MyMethod(3 );  23          } 24      } 25      #endregion  26  27      编译器无法只根据返回值的类型推断出类型 #region  编译器无法只根据返回值的类型推断出类型  28      public   class  MyClass1  29      {  30          public  T MyMethod < T > ()  31          {  return   default (T); }  32      } 33  34      public   class  Class31  35      {  36          public   void  Test()  37          {  38  39              MyClass1 obj =   new  MyClass1();  40              int  number  =  obj.MyMethod < int > ();  41          } 42      } 43      #endregion  44  45      泛型方法约束 #region  泛型方法约束  46      public   class  Class32  47      {  48          public  T MyMethod < T > (T t) where T : IComparable < T >  49          {  return   default (T); }  50      } 51      #endregion  52  53      泛型虚拟方法 #region  泛型虚拟方法  54      public   class  BaseClass33  55      {  56          public   virtual   void  SomeMethod < T > (T t)  57          { }  58      } 59      public   class  SubClass33 : BaseClass33  60      {  61          public   override   void  SomeMethod < T > (T t)  62          {  63              base .SomeMethod < T > (t);  64          } 65      } 66  67      public   class  BaseClass34  68      {  69          public   virtual   void  SomeMethod < T > (T t) where T :  new ()  70          { }  71      } 72      public   class  SubClass34 : BaseClass34  73      {  74          public   override   void  SomeMethod < T > (T t) //  where T : IComparable<T>  75          { }  76      } 77  78      public   class  BaseClass35  79      {  80          public   virtual   void  SomeMethod < T > (T t)  81          { }  82      } 83      public   class  SubClass35 : BaseClass35  84      {  85          public   override   void  SomeMethod < T > (T t)  86          {  87              base .SomeMethod < T > (t);  88              base .SomeMethod(t);  89          } 90      } 91      #endregion  92  93      泛型静态方法 #region  泛型静态方法  94      public   class  MyClass36 < T >  95      {  96          public   static  T SomeMethod(T t)  97          {  return   default (T); }  98      } 99 100      public   class  Class36 101      { 102          public   void  Test() 103          { 104              int  number  =  MyClass36 < int > .SomeMethod( 3 ); 105          }106      }107 108      public   class  MyClass37 < T > 109      { 110          public   static  T SomeMethod < X > (T t, X x) 111          {  return   default (T); } 112      }113      public   class  Class37 114      { 115          public   void  Test() 116          { 117              int  number  =  MyClass37 < int > .SomeMethod < string > ( 3 ,  " AAA " ); 118              int  number1  =  MyClass37 < int > .SomeMethod( 3 ,  " AAA " ); 119          }120      }121 122      public   class  MyClass38 123      { 124          public   static  T SomeMethod < T > (T t) where T : IComparable < T > 125          {   return   default (T); } 126      }127 128      #endregion 129  }130  
4.泛型委托
 1 using  System;  2 using  System.Collections.Generic;  3 using  System.Text;  4  5 namespace  VS2005Demo2  6 {  7      泛型委托 #region  泛型委托  8      public   class  MyClass40 < T >  9      { 10          public   delegate   void  GenericDelegate(T t); 11          public   void  SomeMethod(T t) 12          { } 13      }14 15      public   class  MyClassTest40 16      { 17          public   void  Tests() 18          { 19              MyClass40< int >  obj  =   new  MyClass40 < int > (); 20              MyClass40< int > .GenericDelegate del; 21 22              del =   new  MyClass40 < int > .GenericDelegate(obj.SomeMethod); 23              del(3 ); 24 25              // 委托推理 26             del  =  obj.SomeMethod; 27 28          }29      }30      #endregion 31 32      委托泛型参数 #region  委托泛型参数 33      public   class  MyClass41 < T > 34      { 35          public   delegate   void  GenericDelegate < X > (T t, X x); 36      }37 38      // 外部委托 39      public   delegate   void  GenericDelegate < T > (T t); 40 41      public   class  MyClass42 42      { 43          public   void  SomeMethod( int  number) 44          { } 45      }46 47      public   class  MyClassTest42 48      { 49          public   void  Test() 50          { 51              MyClass42 obj =   new  MyClass42(); 52              GenericDelegate< int >  del; 53              // del = new GenericDelegate<int>(obj.SomeMethod); 54 55              del =  obj.SomeMethod; 56              del(3 ); 57 58          }59      }60 61      #endregion 62 63      委托泛型参数 #region  委托泛型参数 64      public   delegate   void  MyDelegate < T > (T t) where T : IComparable < T > ; 65      #endregion 66 67      事件 #region  事件 68 69      public   delegate   void  GenericEventHandler < S, A > (S sender, A args); 70      71      public   class  MyPublisher 72      { 73          public   event  GenericEventHandler < MyPublisher, EventArgs >  MyEvent; 74          public   void  FireEvent() 75          { 76              MyEvent(this , EventArgs.Empty); 77          }78      }79 80      public   class  MySubscriber < A >   // Optional: can be a specific type 81      { 82          public   void  SomeMethod(MyPublisher sender, A args) 83          { } 84      }85      public   class  MyClassTest43 86      { 87          public   void  Test() 88          { 89              MyPublisher publisher =   new  MyPublisher(); 90              MySubscriber< EventArgs >  subscriber  =   new  MySubscriber < EventArgs > (); 91              publisher.MyEvent +=  subscriber.SomeMethod; 92          }93      }94      #endregion 95  }96  
public   class  Customer {        private   int  _seqnum;        public   int  SequenceNumber  {              get   {  return  _seqnum; }              set   { _seqnum  =  value; }        }       private   string  _name;        public   string  Name  {              get   {  return  _name; }              set   { _name  =  value; }        }       private  DateTime _lastPurchaseDate;        public  DateTime LastPurchaseDate  {              get   {  return  _lastPurchaseDate; }              set   { _lastPurchaseDate  =  value; }        }         public  Customer( int  seqnum,  string  name,          DateTime lastPurchaseDate)  {             SequenceNumber  =  seqnum;             Name  =  name;             LastPurchaseDate  = lastPurchaseDate;       }  }  protected   void  Page_Load( object  sender, EventArgs e)      {         List < Customer >  items  =   new  List < Customer > ();         items.Add( new  Customer( 1 ,  " howard " ,  new  DateTime( 2006 ,  1 ,  1 )));         items.Add( new  Customer( 2 ,  " lee " ,  new  DateTime( 2006 ,  2 ,  1 )));         items.Add( new  Customer( 3 ,  " dierking " ,  new  DateTime( 2006 ,  3 ,  1 )));         items.Add( new  Customer( 4 ,  " jennifer " ,  new  DateTime( 2006 ,  4 ,  1 )));         items.Add( new  Customer( 5 ,  " christine " ,  new  DateTime( 2006 ,  5 ,  1 )));         items.Add( new  Customer( 6 ,  " hannah " ,  new  DateTime( 2006 ,  6 ,  1 )));         items.Add( new  Customer( 7 ,  " leah " ,  new  DateTime( 2006 ,  7 ,  1 )));         items.Add( new  Customer( 8 ,  " anne " ,  new  DateTime( 2006 ,  8 ,  1 )));         items.Add( new  Customer( 9 ,  " dan " ,  new  DateTime( 2006 ,  9 ,  1 )));         items.Add( new  Customer( 10 ,  " mary " ,  new  DateTime( 2006 ,  10 ,  1 )));         Customer ret;          // find customer by a specified name          string  searchName  =   " howard " ;         ret  =  items.Find( delegate (Customer cust)  {  return  cust.Name  ==  searchName; } );                   // find customer by an id          int  searchID  =   4 ;         ret  =  items.Find( delegate (Customer cust)  {  return  cust.SequenceNumber  ==  searchID; } );     }      public  Customer FindCustomerByName(IEnumerable cutsomers,  string  name)      {          foreach  (Customer customer  in  cutsomers)          {              if  (customer.Name  ==  name)              {                  return  customer;             }          }         return   null ;     }  
此方法段本人只是实践一下泛型 + 委托。 < 看不懂要反馈 > delegate  L GetDefaultDomain < L > ( string  domainName); SearchDomain #region  SearchDomain          /**/ ///   <summary>          ///  查找配置文件中的Domain          ///   </summary>          public   static  Dictionary < string ,  string >  SearchDomain()          {             Dictionary < string ,  string >  searchResultDictionary  =   new  Dictionary < string , string > ();             CooperationChannels channelSections  =  Config::ConfigurationManager.GetSection( " CooperationChannels " )  as  CooperationChannels;              foreach  (ChannelProperty data  in  channelSections.Channels)              {                  if  (data.UrlName.Equals(GetServerName()))                  {                     searchResultDictionary.Add( " domainName " , data.DomainName);                     searchResultDictionary.Add( " title " , data.BaseTitle);                      break ;                 }              }             // 默认域名[Ctrip]下 --->   GetDefaultDomain < Dictionary < string ,  string >>  defaultValue  =   delegate ( string  domainName)              {                  if  ( ! searchResultDictionary.TryGetValue( " domainName " ,  out  domainName))                  {                      if  (String.IsNullOrEmpty(domainName)  ==   true )                      {                         searchResultDictionary.Add( " domainName " , ctripDomainName);                         searchResultDictionary.Add( " title " , defaultTitle);                     }                  }                 return  searchResultDictionary;             } ;              return  defaultValue(String.Empty);         }          #endregion  
 
             
            posted @ 
2007-02-13 23:22  
RicoRui  
阅读(
307 ) 
评论() 
 
收藏  
举报