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);
                }
            }
        }
    }

  • 相关阅读:
    ExecuteScalar requires the command to have a transaction when the connection assigned to the command is in a pending
    如何从vss中分离程序
    String or binary data would be truncated
    the pop3 service failed to retrieve authentication type and cannot continue
    The POP3 service failed to start because
    IIS Error he system cannot find the file specified _找不到页面
    pku2575Jolly Jumpers
    pku2940Wine Trading in Gergovia
    pku3219二项式系数
    pku1029false coin
  • 原文地址:https://www.cnblogs.com/dxmfans/p/9434796.html
Copyright © 2011-2022 走看看