是一个拳击转换接口?

时间:2010-06-23 13:14:22

标签: c# oop boxing

我有一个界面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?

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

7 个答案:

答案 0 :(得分:18)

不,因为Employee是一个类,它是reference type而不是value type

来自MSDN

  

拳击是转换的过程   值类型到类型对象或   由此实现的任何接口类型   值类型。当CLR选中一个值时   类型,它包含在一个内部的值   System.Object并将其存储在   托管堆。拆箱提取   来自对象的值类型。

前面提到的MSDN链接还有一些例子可以帮助澄清这个主题。

答案 1 :(得分:9)

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

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

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

答案 2 :(得分:4)

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

答案 3 :(得分:2)

没有

因为emp1是引用类型。

当值类型转换为对象或接口类型时会发生装箱。

答案 4 :(得分:0)

不,不是。

您的Employee实例已经是参考类型。参考类型存储在堆上,因此不需要装箱/取消装箱。

仅当您在堆上存储值类型时才会出现拳击,或者在MSDN语言中,您可以说:

  

拳击是一种隐含的转换   类型的值类型(C#引用)   对象或任何接口类型   由此值类型实现。拳击   值类型分配对象   堆上的实例并复制   值进入新对象。

答案 5 :(得分:0)

不,当您将值类型转换为对象时会发生装箱。

答案 6 :(得分:0)

拳击意味着将值类型转换为对象。您正在将引用类型转换为另一个引用类型,因此这不是装箱转换。