zoukankan      html  css  js  c++  java
  • C# 自定义泛型类,并添加约束

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;


    namespace GenericExam
    {
        class Program
        {
            static void Main(string[] args)
            {
                var dm = new DocumentManager<Document>();
                dm.AddDocument(new Document("Title A","Content A"));
                dm.AddDocument(new Document("Title B","Content B"));
                dm.DisplayAllDocument();


                if (dm.IsDocumentAvailable)
                {
                    Document d = dm.GetDocument();
                    Console.WriteLine(d.Title);
                }
                Console.Read();


            }
        }

    }



    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;


    namespace GenericExam
    {
        public interface IDocument
        {
            string Title { get; set; }
            string Content { get; set; }
        }


        public class Document:IDocument
        {
            public string Title { get; set; }
            public string Content { get; set; }


            public Document(string title, string content)
            {
                this.Title = title;
                this.Content = content;
            }
        }


        public class DocumentManager<T> where T : IDocument
        {
            public Queue<T> DocumentQueue = new Queue<T>();


            public void AddDocument(T doc)
            {
                lock(this)
                {
                    DocumentQueue.Enqueue(doc);
                }
            }


            public bool IsDocumentAvailable
            {
                get { return DocumentQueue.Count > 0; }
            }


            public T GetDocument()
            {
                T doc = default(T);
                lock (this)            
                {               
                    doc = DocumentQueue.Dequeue();
                }
                return doc;
            }


            public void DisplayAllDocument()
            {
                foreach (T doc in DocumentQueue)
                {
                    Console.WriteLine(((IDocument)doc).Title);
                }
            }
        }
    }

  • 相关阅读:
    剑指offer——最小的K个数和数组中第K大的元素
    Leetcode刷题指南链接整理
    160. Intersection of Two Linked Lists
    100. Same Tree
    92. Reverse Linked List II
    94. Binary Tree Inorder Traversal
    79. Word Search
    78,90,Subsets,46,47,Permutations,39,40 DFS 大合集
    0x16 Tire之最大的异或对
    0x16 Tire
  • 原文地址:https://www.cnblogs.com/dxmfans/p/9434796.html
Copyright © 2011-2022 走看看