Using List in C# (Generics)

前端 未结 4 437
灰色年华
灰色年华 2021-02-03 22:25

That\'s a pretty elementary question, but I have never delved into generics before and I found myself in the need to use it. Unfortunately I don\'t have the time right now to go

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-03 22:36

    You need to declare T against the method, then C# can identify the type the method is receiving. Try this:

    void MyMethod(List list){
        //Do stuff
    }
    

    Then call it by doing:

    if (someCondition)
        MyMethod(list1);
    else
        MyMethod(list2);
    

    You can make it even stricter, if all classes you are going to pass to the method share a common base class:

    void MyMethod(List list) where T : MyClassBase
    

提交回复
热议问题