Using List in C# (Generics)

前端 未结 4 435
灰色年华
灰色年华 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:32

    You need to add the generic type parameter for T to your method:

    void MyMethod<T>(List<T> list) {
    

    The compiler doesn't know what T represents, otherwise.

    0 讨论(0)
  • 2021-02-03 22:33

    You need to let c# know what type is sent:

    List<MyClass1> list1 = getListType1();
    List<MyClass2> list2 = getListType2();
    
    if (someCondition)
        MyMethod<MyClass1>(list1);
    else
        MyMethod<MyClass2>(list2);
    
    void MyMethod<T>(List<T> list){
        //Do stuff
    }
    
    0 讨论(0)
  • 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<T>(List<T> 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<T>(List<T> list) where T : MyClassBase
    
    0 讨论(0)
  • 2021-02-03 22:47

    Basically, In C#, List < T > class represents a strongly typed list of objects that can be accessed by index.

    And it also supports storing values of a specific type without casting to or from object.

    we can use in Interger value & String Value in the List.

    0 讨论(0)
提交回复
热议问题