理解C#泛型要好得多 [英] Understanding C# generics much better

查看:100
本文介绍了理解C#泛型要好得多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看了一些使用C#泛型的示例代码。为什么以及何时使用它们?

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

所有示例都很复杂。我需要一个简单明了的例子,让我开始使用C#泛型。

All the examples were complex. I need a simple, clear example that gets me started with C# generics.

推荐答案

一个非常简单的例子是通用的 List< T> class。它可以容纳许多任何类型的对象。例如,您可以声明一个字符串列表( new List ())或一个动物列表( new List< Animal>( )),因为它是通用的。

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

如果您不能使用泛型?您可以使用 ArrayList 类,但缺点是它包含的类型是对象。所以当你迭代列表时,你必须将每个项目转换为正确的类型( string Animal )这是更多的代码,并有性能损失。另外,由于 ArrayList 包含对象,因此它不是类型安全的。您仍然可以向 ArrayList 字符串添加 Animal

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("");

所以当迭代一个ArrayList时,你必须检查类型以确保实例具有特定的类型,导致代码不佳:

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();
}

使用通用的 List< string> ,这根本不可能:

With a generic List<string>, this is simply not possible:

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

这篇关于理解C#泛型要好得多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆