作者andycg (Hank)
看板C_Sharp
標題[問題] List<T> function中增加不同類別的個數
時間Thu Jun 30 10:24:35 2016
各位高手大大好。
想請教一個已經卡關三天了的問題...
已經盡力搜尋,逼不得已才上來求救,請各位幫個忙
---------------------------------------------
我把我的問題修改成簡單理解的方法,另有實際用途
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
→ andycg: 問題已解決 非常感謝二位大大指點 06/30 12:31
→ FancyWing: resize while 用 < 跟 > 就可吧? 為啥要多一個又殺掉? 06/30 23:30
→ FancyWing: 而且 2nd while 用 = 會有問題吧? 06/30 23:32