我有一个IEntity接口
public interface IEntity{
    bool Validate();
}
我有一个实现此接口的类Employee
public class Employee : IEntity{
    public bool Validate(){ return true; }
}
现在,如果我有以下代码
Employee emp1 = new Employee();
IEntity ent1 = (IEntity)emp1; // Is this a boxing conversion?
如果它不是拳击转换那么演员是如何工作的?
在上面的例子中,没有,但有时是的.
拳击是将值类型"装箱"到可引用对象中的过程; 参考类型.在上面的示例中,Employee已经是一个引用类型,因此当您将其强制转换为IEntity时它不会被装箱.
但是,如果Employee是一个值类型,例如struct(而不是类),那么是.
正如其他人所说,将引用类型强制转换为接口不是装箱的示例,而是将值类型强制转换为接口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.
| 归档时间: | 
 | 
| 查看次数: | 2701 次 | 
| 最近记录: |