gpt4 book ai didi

c# - 在 C# 中使用接口(interface)时的值与引用类型

转载 作者:太空狗 更新时间:2023-10-29 17:44:53 28 4
gpt4 key购买 nike

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

为了说明我的情况,我提供了以下接口(interface)示例 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;
}
}

我几乎只使用喜欢的接口(interface)来使用这些类型

I i1 = new ReferenceTypeImplementation(1);
I i2 = new ValueTypeImplementation(1);

ReferenceTypeImplementation 相比,使用 ValueTypeImplementation 有什么优势吗?

最佳答案

Is there any advantage in using ValueTypeImplementation over ReferenceTypeImplementation?

如果您打算通过界面使用它,则不是。正如您所提到的,这会将值类型装箱,这会否定任何潜在的性能改进。

此外,您预期的主要用途将通过接口(interface)这一事实表明您期待引用语义,这再次表明在这种情况下会更合适。

关于c# - 在 C# 中使用接口(interface)时的值与引用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16841921/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com