What is cool about generics, why use them?

2019-01-01 15:10发布

I thought I'd offer this softball to whomever would like to hit it out of the park. What are generics, what are the advantages of generics, why, where, how should I use them? Please, keep it fairly basic. Thanks.

28条回答
梦寄多情
2楼-- · 2019-01-01 15:22

To give a good example. Imagine you have a class called Foo

public class Foo
{
   public string Bar() { return "Bar"; }
}

Example 1 Now you want to have a collection of Foo objects. You have two options, LIst or ArrayList, both of which work in a similar manner.

Arraylist al = new ArrayList();
List<Foo> fl = new List<Foo>();

//code to add Foos
al.Add(new Foo());
f1.Add(new Foo());

In the above code, if I try to add a class of FireTruck instead of Foo, the ArrayList will add it, but the Generic List of Foo will cause an exception to be thrown.

Example two.

Now you have your two array lists and you want to call the Bar() function on each. Since hte ArrayList is filled with Objects, you have to cast them before you can call bar. But since the Generic List of Foo can only contain Foos, you can call Bar() directly on those.

foreach(object o in al)
{
    Foo f = (Foo)o;
    f.Bar();
}

foreach(Foo f in fl)
{
   f.Bar();
}
查看更多
若你有天会懂
3楼-- · 2019-01-01 15:24

I know this is a C# question, but generics are used in other languages too, and their use/goals are quite similar.

Java collections use generics since Java 1.5. So, a good place to use them is when you are creating your own collection-like object.

An example I see almost everywhere is a Pair class, which holds two objects, but needs to deal with those objects in a generic way.

class Pair<F, S> {
    public final F first;
    public final S second;

    public Pair(F f, S s)
    { 
        first = f;
        second = s;   
    }
}  

Whenever you use this Pair class you can specify which kind of objects you want it to deal with and any type cast problems will show up at compile time, rather than runtime.

Generics can also have their bounds defined with the keywords 'super' and 'extends'. For example, if you want to deal with a generic type but you want to make sure it extends a class called Foo (which has a setTitle method):

public class FooManager <F extends Foo>{
    public void setTitle(F foo, String title) {
        foo.setTitle(title);
    }
}

While not very interesting on its own, it's useful to know that whenever you deal with a FooManager, you know that it will handle MyClass types, and that MyClass extends Foo.

查看更多
春风洒进眼中
4楼-- · 2019-01-01 15:24

From the Sun Java documentation, in response to "why should i use generics?":

"Generics provides a way for you to communicate the type of a collection to the compiler, so that it can be checked. Once the compiler knows the element type of the collection, the compiler can check that you have used the collection consistently and can insert the correct casts on values being taken out of the collection... The code using generics is clearer and safer.... the compiler can verify at compile time that the type constraints are not violated at run time [emphasis mine]. Because the program compiles without warnings, we can state with certainty that it will not throw a ClassCastException at run time. The net effect of using generics, especially in large programs, is improved readability and robustness. [emphasis mine]"

查看更多
浪荡孟婆
5楼-- · 2019-01-01 15:26

Generics allow you to create objects that are strongly typed, yet you don't have to define the specific type. I think the best useful example is the List and similar classes.

Using the generic list you can have a List List List whatever you want and you can always reference the strong typing, you don't have to convert or anything like you would with a Array or standard List.

查看更多
呛了眼睛熬了心
6楼-- · 2019-01-01 15:26

If your collection contains value types, they don't need to box/unbox to objects when inserted into the collection so your performance increases dramatically. Cool add-ons like resharper can generate more code for you, like foreach loops.

查看更多
若你有天会懂
7楼-- · 2019-01-01 15:27

I just like them because they give you a quick way to define a custom type (as I use them anyway).

So for example instead of defining a structure consisting of a string and an integer, and then having to implement a whole set of objects and methods on how to access an array of those structures and so forth, you can just make a Dictionary

Dictionary<int, string> dictionary = new Dictionary<int, string>();

And the compiler/IDE does the rest of the heavy lifting. A Dictionary in particular lets you use the first type as a key (no repeated values).

查看更多
登录 后发表回答