是一个拳击转换界面?
我有一个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
是一个类,它是引用类型而不是值类型 。
来自MSDN :
Boxing是将值类型转换为类型对象或由此值类型实现的任何接口类型的过程。 当CLR选择一个值类型时,它将值包装在System.Object中并将其存储在托管堆上。 取消装箱从对象中提取值类型。
上述MSDN链接还有其他示例,有助于澄清该主题。
在上面的例子中,没有,但有时是的。
拳击是将值类型“装箱”到可引用对象的过程; 参考类型。 在上面的示例中,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.
没有。
因为emp1是引用类型。
当值类型转换为对象或接口类型时发生拳击。
不,这不对。
您的Employee实例已经是参考类型。 引用类型存储在堆上,因此不需要装箱/取消装箱。
拳击只在您在堆上存储值类型时发生,或者在MSDN语言中,您可以说:
Boxing是将值类型(C#引用)隐式转换为类型对象或由此值类型实现的任何接口类型。 装箱值类型在堆上分配对象实例并将值复制到新对象中。
拳击意味着将值类型转换为对象。 您正在将引用类型转换为另一个引用类型,因此这不是装箱转换。
不,当您将值类型转换为对象时会发生装箱。