C#中泛型特性1-默认值

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace 泛型
  6. {
  7.     // 泛型特性:1默认值
  8.     class 泛型的特性
  9.     {
  10.         public static void Main()
  11.         {
  12.             DocumentManager<string> manager = new DocumentManager<string>();
  13.             manager.AddDocument( "aladdin");
  14.             manager.AddDocument("zhao");
  15.             manager.AddDocument("jacky");
  16.             Console.WriteLine( manager.IsDocumentAvailable );
  17.             //取从前面开始取队列中的值
  18.             Console.WriteLine(manager.GetDocument());
  19.             Console.WriteLine(manager.GetDocument());
  20.             Console.WriteLine(manager.GetDocument());
  21.             Console.ReadLine();   
  22.         }
  23.     }
  24.     class DocumentManager<T>
  25.     { 
  26.         //表示对象先进先出的集合
  27.         private readonly Queue<T> documentQueue = new Queue<T>() ;
  28.         public void AddDocument(T doc)
  29.         {
  30.             lock (this)
  31.             {
  32.                 documentQueue.Enqueue(doc);
  33.             }
  34.         }
  35.         public bool IsDocumentAvailable
  36.         {
  37.             get { return documentQueue.Count > 0; } 
  38.         }
  39.         public T GetDocument()
  40.         { 
  41.             //1泛型的默认值特性
  42.             //用default关键字,这样他既可处理null,也可以处理值类型的0为默认
  43.             T doc = default(T) ;
  44.             lock (this)
  45.             {
  46.                 doc = documentQueue.Dequeue();
  47.             }
  48.             return doc;
  49.         }
  50.     }
  51. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值