看板 C_Sharp 關於我們 聯絡資訊
剛google到這篇 https://msdn.microsoft.com/zh-tw/library/d5x73970.aspx 在Employee的例子中Employee有Name屬性, 對於下方的這個泛型類別 public class GenericList<T> where T : Employee public T Data { get { return data; } set { data = value; } } ....中略... while (current != null) { //The constraint enables access to the Name property. if (current.Data.Name == s) { t = current.Data; break; } ...後略 他底下給的解釋是 該條件約束可讓泛型類別使用 Employee.Name 屬性, 因為型別 T 的所有項目都一定會是 Employee 物件, 或繼承自 Employee 的物件。 所以應該 Employee 跟 有繼承Employee的類別 都可以被使用or加入 下個例子 class EmployeeList<T> where T : Employee, IEmployee, System.IComparable<T>, new() 解釋 只要使用 條件約束型別 和 其繼承階層架構內的所有型別, 運算和方法呼叫都會受到支援。 看完理解大概如此 介面的部分剛才試了一下 IB:IA, IB就算沒有宣告IA裡的方法, C : IB 還是需要同時實作IB 和IA裡的方法 不然會錯 所以沒宣告一樣要實作 >> 不宣告不影響最終效果 http://i.imgur.com/XsYViel.png
再試了下如果在B重複宣告A裡的方法,照看到的提示, 這樣做好像是會把A的方法屏蔽掉,所以他建議要加new 但我沒加new還是build的過,所以或許不加new效果上沒差 http://i.imgur.com/oGC4Eme.png
(有錯請告知..) ※ 引述《wwe90425 (撒尿牛丸)》之銘言: : 之前看深入淺出c#有提到 : 如果有繼承介面的話,一定要實作介面的方法或屬性 : 但這幾天上班看到同事寫的程式碼時 : 卻發現沒有實作介面類別理的方法,卻可以順利compile沒報錯 : 想請問一下這是什麼原因? : 附上程式碼: : 介面: : public interface IRepository<T> where T : class : { : IQueryable<T> GetAll(); : T GetById(int id); : void Add(T entity); : void Update(T entity); : void Delete(T entity); : void Delete(int id); : } : 繼承介面的類別: : public interface IRepoPostSubDtl : IRepository<T_PostSubDtl> : { : } : 另外想請問一下where T : class這是什麼意思 : 請高手幫忙解答,感謝~ -- ~ Sent from my PCMan Combo ~ -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.36.98.193 ※ 文章網址: https://www.ptt.cc/bbs/C_Sharp/M.1484485100.A.1EE.html ※ 編輯: name2name2 (114.36.98.193), 01/15/2017 21:09:46
kalaja: https://goo.gl/Kqup0T msdn 有解釋這樣的情況。 01/15 21:23
kalaja: 不同介面但有相同名稱方法,也可實作被屏蔽掉的介面。 01/15 21:28
原來如此! ※ 編輯: name2name2 (114.36.98.193), 01/15/2017 21:56:27
CloudyWing: 不加new遇到同名就會預設Hide,加new就是告訴編譯器要H 01/18 14:58
CloudyWing: ide 01/18 14:58