"Generics add stability to your code by making more of your bugs detectable at compile time." - 通俗易懂的解释?

"Generics add stability to your code by making more of your bugs detectable at compile time." - Explained in laymen's terms?

"Generics add stability to your code by making more of your bugs detectable at compile time."

我一直在到处阅读这篇文章,但我似乎无法找到解释为什么泛型有助于在编译时而不是 运行 时间更容易检测到错误。

也许这可能会在其他地方得到解答,但如果有人愿意花时间用通俗易懂的方式解释一下,我将不胜感激。我将能够理解那些其他的解释,如果你这样做!

想象一下这个场景:

public class Bob(){}
public Class Tom(){}

List list = new List();
list.Add(new Bob());
list.Add(new Tom());
Tom tom = (Tom)list[0]; //oops wrong index

这会失败,但只会在 运行 时失败,因为 Bob 不是 Tom

List<Bob> list = new List<Bob>();
list.Add(new Bob());

Tom tom = list[0];

这将在编译时失败,因为编译器可以判断列表只能包含 Bob,因此最后一条语句无效,因为您不可能得到 Tom列表的列表,因为它是一个只能包含 Bobs.

的列表

类似地,这段代码也会在编译时失败:

list.Add(new Tom());

因为该列表被声明为 Bob 的列表,而您正在尝试添加 Tom

泛型允许编译器知道代码正在处理什么类型,因此可以防止您尝试使用对上下文无效的类型。

所以对于泛型,你基本上是在对编译器说(在上面的例子中):

I have a list. Its a list of Bobs. Please only allow me to put Bob instances into the list and make it an error if I try and put any other type into the list.

完成此操作后,您就不会无意中向列表中添加任何其他内容。如果将列表传递给函数并在远离声明它的地方使用它,这会很容易做到。

一般来说,泛型就像是一种告诉编译器一些关于您正在处理的类型的额外信息的方法,这样它可以帮助您避免错误地使用类型