3

Since many years, we use generic collections most of the time. Sometimes we really do need a collection of anything (well, usually only a few different things but with no common base class). For such circumstances we can use either IList or the generic IList<object> as type for method arguments and properties.

Is there any reason to prefer one over the other? Performance characteristics?

Personally, I'm leaning towards IList<object>, as I think this makes it more clear that we really do accept "anything". When a parameter is typed as IList we cannot immediately tell if this method do accept anything, or if the lack of generics is due to history or sloppy coding.


There's a good reason: LINQ and its extension methods. These aren't implemented for pre-generics era types. You will need to call Cast<T> on the IList to take advantage of LINQ!

Other point is that, since newest .NET versions support covariance and contravariance and most of generic interfaces support one or the other (f.e. IEnumerable<out T>, T is covariant), you can easily downcast or upcast interfaces' generic parameters from and to object or a less-unspecific type.

Conclusion: why generics should be prefered?

  • Generic types have better performance because they avoid a lot of casts.
  • Newer APIs rely on generic collections and interfaces.
  • There're a lot of reasons to think that mixing objects of different types in the same list could be dangerous and a bad coding/design decision. And for the few cases where you'll store any kind of object, having LINQ and many other newer APIs and features as your friend is a powerful reason to don't reinvent wheels and save a lot of time!
4

1 回答 1

5

有一个很好的理由:LINQ 及其扩展方法。这些不适用于泛型之前的时代类型。您需要调用Cast<T>LINQ IList

另一点是,由于最新的 .NET 版本支持协变和逆变,并且大多数泛型接口都支持其中一种(feIEnumerable<out T>T协变的),因此您可以轻松地将接口的泛型参数向下转换或向上转换到对象或不特定的对象类型。

结论:为什么应该首选泛型?

  • 泛型类型具有更好的性能,因为它们避免了很多强制转换。
  • 较新的 API 依赖于通用集合和接口。
  • 有很多理由认为在同一个列表中混合不同类型的对象可能是危险的,并且是一个糟糕的编码/设计决策。对于您将存储任何类型的对象的少数情况,拥有 LINQ 和许多其他较新的 API 和功能作为您的朋友是不重新发明轮子并节省大量时间的有力理由!
于 2013-02-24T11:17:03.940 回答