C#自定義泛型型別集合
阿新 • • 發佈:2018-12-24
一.定義介面
public interface ICustom
{
string Title { get; set; }
string Content { get; set; }
}
二.實現介面
public class Custom : ICustom { public string Title { get; set; } public string Content { get; set; } public Custom() { } public Custom(string title, string content) { this.Title = title; this.Content = content; } }
三.集合結果處理
public class CustomSet<T> where T : ICustom { /// <summary> /// 定義儲存集合 /// </summary> private readonly Queue<T> newQue = new Queue<T>(); /// <summary> /// 新增內容 /// </summary> /// <param name="info"></param> public void AddCustom(T info) { lock (this) { newQue.Enqueue(info); } } /// <summary> /// 驗證是否向自定義集合中儲存資料 /// </summary> public bool IsCustomSetValidate => newQue.Count > 0; /// <summary> /// 返回集合的最後一個結果 /// </summary> /// <returns></returns> public T GetCustomSet() { T doc = default(T); lock (this) { doc = newQue.LastOrDefault(); } return doc; } /// <summary> /// 輸出資料集合 /// </summary> /// <returns></returns> public void GetAllCustomSet() { foreach (T que in newQue) { Console.WriteLine(que.Title); } } }
四.呼叫測試
CustomSet<Custom> custom = new CustomSet<Custom>(); custom.AddCustom(new Custom { Title = "CUSTOMTITLEA", Content = "CUSTOMCONTENTA" }); custom.AddCustom(new Custom { Title = "CUSTOMTITLEB", Content = "CUSTOMCONTENTB" }); custom.GetAllCustomSet(); Console.WriteLine(custom.IsCustomSetValidate ? custom.GetCustomSet().Content : null);