小编brd*_*lph的帖子

在C#中使用接口时的值与引用类型

我想在C#中创建一个类似语义的类型.它是不可变的,内存占用少.但是,它主要通过它实现的接口访问.在这种情况下,必须将值类型装箱,这意味着必须将实际值从堆栈复制到堆中.因此,我想知道使用值类型(struct)而不是引用类型(类)是否有任何优势?

为了说明我的情况,我提供了一个接口下面的例子I与实现ReferenceTypeImplementationValueTypeImplementation:

interface I
{
    int GetSomeInt();
}

class ReferenceTypeImplementation : I
{
    public readonly int i;

    public ReferenceTypeImplementation (int i)
    {
        this.i = i;
    }

    public int GetSomeInt()
    {
        return i*2;
    }
}

struct ValueTypeImplementation : I
{
    public readonly int i;

    public ValueTypeImplementation (int i)
    {
        this.i = i;
    }

    public int GetSomeInt()
    {
        return i*2;
    }
}
Run Code Online (Sandbox Code Playgroud)

我会使用的界面几乎完全使用这些类型的I

I i1 = new ReferenceTypeImplementation(1);
I i2 = new ValueTypeImplementation(1);
Run Code Online (Sandbox Code Playgroud)

使用 …

c# struct boxing interface class

9
推荐指数
1
解决办法
1245
查看次数

标签 统计

boxing ×1

c# ×1

class ×1

interface ×1

struct ×1