正如其他人所说,将引用类型转换为接口不是装箱的示例,而是将值类型转换为接口 IS。
public interface IEntity {
bool Validate();
}
public class EmployeeClass : IEntity {
public bool Validate() { return true; }
}
public struct EmployeeStruct : IEntity {
public bool Validate() { return true; }
}
//Boxing: A NEW reference is created on the heap to hold the struct's memory.
//The struct's instance fields are copied into the heap.
IEntity emp2 = new EmployeeStruct(); //boxing
//Not considered boxing: EmployeeClass is already a reference type, and so is always created on the heap.
//No additional memory copying occurs.
IEntity emp1 = new EmployeeClass(); //NOT boxing
//unboxing: Instance fields are copied from the heap into the struct.
var empStruct = (EmployeeStruct)emp2;
//empStruct now contains a full shallow copy of the instance on the heap.
//no unboxing. Instance fields are NOT copied.
var empClass = (EmployeeClass)emp2; //NOT unboxing.
//empClass now points to the instance on the heap.