通过引用传递 C# 值类型以避免装箱 [英] Passing C# value type by reference to avoid boxing

查看:67
本文介绍了通过引用传递 C# 值类型以避免装箱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C# 中避免装箱的一种方法是通过引用传递值类型.我已经读过 通用方法也可以使用避免拳击.尽管仅仅为了避免装箱而编写泛型方法似乎有点极端——如果类型总是相同的话.

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.

我的问题是 - 如果编写代码以获得最佳性能并避免装箱,通过引用传递所有值类型(如 int)是否合理 - 即使有问题的方法仅适用于对象而不是创建它?这有什么缺点吗?

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?

推荐答案

避免值类型装箱的最佳方法是:将它们用作值!

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

我认为您完全误读了该参考文献.它说的是使用 ref 参数不会导致装箱.这并不是说这是一种避免拳击的方法.

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.

280Z28 总结:

换句话说,避免以下两种操作:

In other words, avoid the following two operations:

  1. 将值强制转换或分配给 object 类型的变量(或将值作为参数传递给 object 类型的方法参数).
  2. 将值强制转换或分配给 接口 类型(例如 IEnumerable)的变量,或将值作为方法参数的参数传递,该方法参数是一个接口类型.
  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.

这篇关于通过引用传递 C# 值类型以避免装箱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆