看板 C_Sharp 關於我們 聯絡資訊
各位高手大大好。 想請教一個已經卡關三天了的問題... 已經盡力搜尋,逼不得已才上來求救,請各位幫個忙 --------------------------------------------- 我把我的問題修改成簡單理解的方法,另有實際用途 public class Parent {...} public class Child01 : Parent {...} public class Child02 : Parent {...} ... class main { List<Child01> C1 = new List<Child01>(); List<Child02> C2 = new List<Child02>(); public static void Main() { Resize<Child01>(C1, 30); Resize<Child02>(C2, 50); } void Resize<T>(List<T> list, int count) { while(list.count <= count) list.Add(new T); while(list.count >= count) list.RemoveAt(count); } } ------------------------------- 想請問Resize這個function的正確寫法、 以及在.Add()中的new正確寫法 如果是一般變數T的用法還行,網路上基礎教學很多 但是配上List後變得不知道怎麼寫... 懇請各位大大指教,由衷感謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 101.138.173.202 ※ 文章網址: https://www.ptt.cc/bbs/C_Sharp/M.1467253477.A.189.html
ssccg: 在方法定義加上 where T : new() 06/30 11:00
ssccg: 然後用 new T() 06/30 11:00
YahooTaiwan: 泛型類型條件約束 06/30 11:34
YahooTaiwan: http://tinyurl.com/j6wccld 06/30 11:34
andycg: 問題已解決 非常感謝二位大大指點 06/30 12:31
FancyWing: resize while 用 < 跟 > 就可吧? 為啥要多一個又殺掉? 06/30 23:30
FancyWing: 而且 2nd while 用 = 會有問題吧? 06/30 23:32