Understanding C# generics much better

前端 未结 4 1098
没有蜡笔的小新
没有蜡笔的小新 2020-12-08 07:32

I looked at some sample code using C# generics. Why and when should I use them?

All the examples were complex. I need a simple, clear example that gets me started wi

4条回答
  •  难免孤独
    2020-12-08 07:52

    A very simple example is the generic List class. It can hold a number of objects of any type. For example, you can declare a list of strings (new List()) or a list of Animals (new List()), because it is generic.

    What if you couldn't use generics? You could use the ArrayList class, but the downside is that it's containing type is an object. So when you'd iterate over the list, you'd have to cast every item to its correct type (either string or Animal) which is more code and has a performance penalty. Plus, since an ArrayList holds objects, it isn't type-safe. You could still add an Animal to an ArrayList of strings:

    ArrayList arrayList = new ArrayList();
    arrayList.Add(new Animal());
    arrayList.Add("");
    

    So when iterating an ArrayList you'd have to check the type to make sure the instance is of a specific type, which results in poor code:

    foreach (object o in arrayList)
    {
      if(o is Animal)
        ((Animal)o).Speak();
    }
    

    With a generic List, this is simply not possible:

    List stringList = new List();
    stringList.Add("Hello");
    stringList.Add("Second String");
    stringList.Add(new Animal()); // error! Animal cannot be cast to a string
    

提交回复
热议问题