[問題] 如何將傳入的泛型資料存起來? (已解決)
public class GenericTest
{
private List<int> intList;
public void Set<T>(List<T> list)
{
//外部呼叫此方法,傳入List<T>
//然後將此list給存下來
//類似intList = list之類的
}
}
在其他Script會呼叫Set<T>(),將一個List<T>給丟過來
請問如何正確地把該List<T>給存起來?
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 211.75.116.70
※ 文章網址: https://www.ptt.cc/bbs/C_Sharp/M.1502420876.A.BA8.html
※ 編輯: brian780405 (211.75.116.70), 08/11/2017 11:08:39
→
08/11 11:20, , 1F
08/11 11:20, 1F
→
08/11 11:20, , 2F
08/11 11:20, 2F
intList那段是打個比喻,如果list是List<int>才用intList存
主要的問題是呼叫Set的那一方知道T是什麼
但收到list的這邊要怎樣知道T是什麼?然後把他存下來?
這邊我一直搞不懂...
※ 編輯: brian780405 (211.75.116.70), 08/11/2017 11:40:13
推
08/11 12:11, , 3F
08/11 12:11, 3F
推
08/11 12:13, , 4F
08/11 12:13, 4F
→
08/11 12:13, , 5F
08/11 12:13, 5F
→
08/11 12:13, , 6F
08/11 12:13, 6F
→
08/11 13:13, , 7F
08/11 13:13, 7F
我知道可以用typeof去判斷T,然後就不知道怎麼做了
又不能把T強制轉型成int之類的...
※ 編輯: brian780405 (211.75.116.70), 08/11/2017 13:32:33
推
08/11 17:44, , 8F
08/11 17:44, 8F
→
08/11 18:56, , 9F
08/11 18:56, 9F
→
08/11 18:57, , 10F
08/11 18:57, 10F
我做的東西的Set<T>是繼承介面後實做出來的,這篇發文沒提到就是了...
重複看了s大的回文後,想到只要把介面定成泛型介面
這樣就可以達到我的需求
public interface ISet<T> {
void Set<T>(List<T> list);
}
public class GenericTest : ISet<int>
{
private List<int> intList;
public void Set(List<int> list)
{
intList = list;
}
}
當初也沒表達清楚就是了...
感謝各位鄉民的幫忙
※ 編輯: brian780405 (114.32.35.69), 08/14/2017 22:40:05