我试图收集所有在 C # 中发生拳击的情况:
将值类型转换为 System.Object
类型:
struct S { }
object box = new S();
Converting value type to System.ValueType
type:
struct S { }
System.ValueType box = new S();
Converting value of enumeration type to System.Enum
type:
enum E { A }
System.Enum box = E.A;
Converting value type into interface reference:
interface I { }
struct S : I { }
I box = new S();
Using value types in C# string concatenation:
char c = F();
string s1 = "char value will box" + c;
注意: char
类型的常量在编译时被连接起来
注意: 自从6.0 C # 编译器 优化连接涉及到 bool
,char
,IntPtr
,UIntPtr
类型
从值类型实例方法创建委托:
struct S { public void M() {} }
Action box = new S().M;
Calling non-overridden virtual methods on value types:
enum E { A }
E.A.GetHashCode();
Using C# 7.0 constant patterns under is
expression:
int x = …;
if (x is 42) { … } // boxes both 'x' and '42'!
Boxing in C# tuple types conversions:
(int, byte) _tuple;
public (object, object) M() {
return _tuple; // 2x boxing
}
Optional parameters of object
type with value type default values:
void M([Optional, DefaultParameterValue(42)] object o);
M(); // boxing at call-site
Checking value of unconstrained generic type for null
:
bool M<T>(T t) => t != null;
string M<T>(T t) => t?.ToString(); // ?. checks for null
M(42);
注意: 在某些.NET 运行时中,这可能会被 JIT 优化
使用 is
/as
运算符的无约束或 struct
通用类型的类型测试值:
bool M<T>(T t) => t is int;
int? M<T>(T t) => t as int?;
IEquatable<T> M<T>(T t) => t as IEquatable<T>;
M(42);
注意: 在某些.NET 运行时中,这可能会被 JIT 优化
据你所知,还有其他类似拳击的情况吗?