Boxing and unboxing: when does it come up?

前端 未结 7 974
灰色年华
灰色年华 2020-12-01 11:22

So I understand what boxing and unboxing is. When\'s it come up in real-world code, or in what examples is it an issue? I can\'t imagine doing something like this example:

7条回答
  •  醉酒成梦
    2020-12-01 11:49

    It's much less of an issue now than it was prior to generics. Now, for example, we can use:

    List x = new List();
    x.Add(10);
    int y = x[0];
    

    No boxing or unboxing required at all.

    Previously, we'd have had:

    ArrayList x = new ArrayList();
    x.Add(10); // Boxing
    int y = (int) x[0]; // Unboxing
    

    That was my most common experience of boxing and unboxing, at least.

    Without generics getting involved, I think I'd probably say that reflection is the most common cause of boxing in the projects I've worked on. The reflection APIs always use "object" for things like the return value for a method - because they have no other way of knowing what to use.

    Another cause which could catch you out if you're not aware of it is if you use a value type which implements an interface, and pass that value to another method which has the interface type as its parameter. Again, generics make this less of a problem, but it can be a nasty surprise if you're not aware of it.

提交回复
热议问题