C#: System.Object vs Generics

前端 未结 8 947
别那么骄傲
别那么骄傲 2020-11-30 05:48

I\'m having a hard time understanding when to use Object (boxing/unboxing) vs when to use generics.

For example:

public class Stack 
{
    int positi         


        
8条回答
  •  清歌不尽
    2020-11-30 06:17

    While there are times when you will want to use a non-generic collection (think caching, for instance), you almost always have collections of homogenous objects not heterogenous objects. For a homogenous collection, even if it is a collection of variants of base type or interface, it's always better to use generics. This will save you from having to cast the result as the real type before you can use it. Using generics makes your code more efficient and readable because you can omit the code to do the cast.

提交回复
热议问题