Passing C# value type by reference to avoid boxing

ぐ巨炮叔叔 提交于 2020-01-17 18:01:07

问题


One way to avoid boxing in C# is to pass the value type by reference. I have read that a generic method can also be used to avoid boxing. Although writing a generic method solely for the purpose of avoiding boxing seems to be a little extreme - if the type will always be the same.

My question is - if writing code for the best performance and to avoid boxing, is it reasonable to pass all value types (like an int) by reference - even though the method in question is only working on the object and not creating it? Are there any drawbacks to this?


回答1:


The best way to avoid boxing of value types is: just use them as values!

I think you have completely misread that reference. What it says is that using ref parameters does not cause boxing. It does not say that it is a way to avoid boxing.

Boxing happens when a value type is used in a reference context, such as being cast to an Object. This article says that passing parameters by reference must not be confused with the concept of reference types, but confuse them seems to be exactly what you've done.

Summary by 280Z28:

In other words, avoid the following two operations:

  1. Casting or assigning the value to a variable of type object (or passing the value as an argument for a method parameter of type object).
  2. Casting or assigning the value to a variable which is an interface type (such as IEnumerable), or passing the value as an argument for a method parameter which is an interface type.

There are exceptions to this rule (e.g. calling some generic methods), and there are cases where boxing can occur in other contexts, but these are the primary situations to be aware of when you are trying to avoid unnecessary boxing of value types.



来源:https://stackoverflow.com/questions/25902154/passing-c-sharp-value-type-by-reference-to-avoid-boxing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!