Collections and Generics

 

1. Interface layout

2. the .NET platform supports two broad groups of data types, termed value types and reference types. C# provides a very simple mechanism, termed boxing, to convert a value type to a reference
type.

 

3. In summary, generic containers provide the following benefits over their nongeneric counterparts:
• Generics provide better performance, as they do not result in boxing or unboxing penalties.
• Generics are more type safe, as they can only contain the “type of type” you specify.
• Generics greatly reduce the need to build custom collection types, as the base class library provides several prefabricated containers.

 

4. With the introduction of generics, the C# default keyword has been given a dual identity. In addition to its use within a switch construct, it can be used to set a type parameter to its default value. This is clearly helpful given that a generic type does not know the actual placeholders up front and therefore cannot safely assume what the default value will be. The defaults for a type parameter are as follows:
• Numeric values have a default value of 0.
• Reference types have a default value of null.
• Fields of a structure are set to 0 (for value types) or null (for reference types).

  1.    1. // The "default" keyword is overloaded in C#.  
  2.    2. // When used with generics, it represents the default  
  3.    3. // value of a type parameter.  
  4.    4. public void ResetPoint()  
  5.    5. {  
  6.    6.     xPos = default(T);  
  7.    7.     yPos = default(T);  
  8.    8. }  

 

5.

  1.    1. // MyGenericClass derives from Object, while  
  2.    2. // contained items must have a default ctor.  
  3.    3. public class MyGenericClass<T> where T : new()  
  4.    4. {...}  
  5.    5. // MyGenericClass derives from Object, while  
  6.    6. // contained items must be a class implementing IDrawable  
  7.    7. // and support a default ctor.  
  8.    8. public class MyGenericClass<T> where T : class, IDrawable, new()  
  9.    9. {...}  
  10.   10. // MyGenericClass derives from MyBase and implements ISomeInterface,  
  11.   11. // while the contained items must be structures.  
  12.   12. public class MyGenericClass<T> : MyBase, ISomeInterface where T : struct  
  13.   13. {...}  
  14.   14. // <K> must have a default ctor, while <T> must  
  15.   15. // implement the generic IComparable interface.  
  16.   16. public class MyGenericClass<K, T> where K : new()  
  17.   17. where T : IComparable<T>  
  18.   18. {...}  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值