C#: System.Object vs Generics

前端 未结 8 953
别那么骄傲
别那么骄傲 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:30

    Use generics when you want your structure to handle a single type. For example, if you wanted a collection of strings you would want to instantiate a strongly typed List of strings like so:

    List myStrings = new List();
    

    If you want it to handle multiple types you can do without generics but you will incur a small performance hit for boxing/unboxing operations.

提交回复
热议问题