是一个拳击转换接口?

Hem*_*jak 13 c# oop boxing

我有一个IEntity接口

public interface IEntity{
    bool Validate();
}
Run Code Online (Sandbox Code Playgroud)

我有一个实现此接口的类Employee

public class Employee : IEntity{
    public bool Validate(){ return true; }
}
Run Code Online (Sandbox Code Playgroud)

现在,如果我有以下代码

Employee emp1 = new Employee();
IEntity ent1 = (IEntity)emp1; // Is this a boxing conversion?
Run Code Online (Sandbox Code Playgroud)

如果它不是拳击转换那么演员是如何工作的?

Ahm*_*eed 18

不,因为Employee是一个类,它是一个引用类型而不是值类型.

来自MSDN:

Boxing是将值类型转换为类型对象或由此值类型实现的任何接口类型的过程.当CLR选中一个值类型时,它将值包装在System.Object中并将其存储在托管堆上.取消装箱从对象中提取值类型.

上述MSDN链接还有其他示例,有助于澄清该主题.


Rob*_*ine 9

在上面的例子中,没有,但有时是的.

拳击是将值类型"装箱"到可引用对象中的过程; 参考类型.在上面的示例中,Employee已经是一个引用类型,因此当您将其强制转换为IEntity时它不会被装箱.

但是,如果Employee是一个值类型,例如struct(而不是类),那么是.


drw*_*ode 5

正如其他人所说,将引用类型强制转换为接口不是装箱的示例,而是将值类型强制转换为接口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.
Run Code Online (Sandbox Code Playgroud)