结构、接口和装箱 [英] Structs, Interfaces and Boxing

查看:18
本文介绍了结构、接口和装箱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
结构体实现接口是否安全?

拿这个代码:

interface ISomeInterface
{
    public int SomeProperty { get; }
}

struct SomeStruct : ISomeInterface
{
    int someValue;

    public int SomeProperty { get { return someValue; } }

    public SomeStruct(int value)
    {
        someValue = value;
    }
}

然后我在某处这样做:

ISomeInterface someVariable = new SomeStruct(2);

在这种情况下 SomeStruct 是否被装箱?

is the SomeStruct boxed in this case?

推荐答案

是的.基本上,每当您需要一个引用而您只有一个值类型值时,该值就会被装箱.

Yes, it is. Basically whenever you need a reference and you've only got a value type value, the value is boxed.

这里的ISomeInterface是一个接口,是一个引用类型.因此someVariable的值总是一个引用,所以新创建的struct值必须被装箱.

Here, ISomeInterface is an interface, which is a reference type. Therefore the value of someVariable is always a reference, so the newly created struct value has to be boxed.

这篇关于结构、接口和装箱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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