投射到接口是拳击转换吗? [英] Is casting to an interface a boxing conversion?

查看:70
本文介绍了投射到接口是拳击转换吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接口IEntity

I have an interface IEntity

public interface IEntity{
    bool Validate();
}

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

And I have a class Employee which implements this interface

public class Employee : IEntity{
    public bool Validate(){ return true; }
}

现在,如果我有以下代码

Now if I have the following code

Employee emp1 = new Employee();
IEntity ent1 = (IEntity)emp1; // Is this a boxing conversion?

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

If it is not a boxing conversion then how does the cast work?

推荐答案

否,因为Employee是一个类,它是一个值类型.

No, since Employee is a class, which is a reference type rather than a value type.

来自 MSDN :

装箱是转换 值类型到类型对象或 由此实现的任何接口类型 值类型.当CLR框显示一个值时 类型,它将值包装在 System.Object并将其存储在 托管堆.拆箱提取 对象中的值类型.

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing extracts the value type from the object.

前面提到的MSDN链接提供了更多示例,这些示例应该有助于阐明该主题.

The aforementioned MSDN link has further examples that should help clarify the topic.

这篇关于投射到接口是拳击转换吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆