C# 中的任何内置值类型是否实现任何接口?

huangapple go评论68阅读模式
英文:

Does any built-in value type in C# implement any interface?

问题

我在C#中学习拳击。如果值类型(如结构体)实现了一个接口,那么当我们将一个结构体类型的对象分配给已由结构体实现的接口类型的变量时,会发生装箱操作。

现在我的问题是,是否有任何内置的值类型,如 "int" 或 "double",已经实现了任何接口?

英文:

I'm studying Boxing in C#. And it says if a value type such as a struct implements an interface, there is a boxing operation when we assign an object of type struct to a variable of the type of the interface that has been implemented by the struct.

Now this is my question. Is there any built-in value type such as "int" or "double" that has implemented any interface?

答案1

得分: 2

是的,标准的数值类型实现了相当多的接口,具体包括 IEquatableIComparableIConvertible。在 .NET 7.0 中,为了支持通用数学,添加了更多接口。

如果您像这样做:

int x = 2;
IEquatable<int> eq = x;
if (eq.Equals(3))
{
    // ...
}

则需要进行装箱转换。但是,如果您像这样编写:

int x = 2;
if (x.Equals(3))
{
    // ...
}

编译器通常会直接调用 Equals 方法,避免了装箱。当然,如果您简单地编写 if (x == 3),也不涉及装箱,因为编译器直接插入了数值相等测试的指令。

英文:

Yes, the standard numeric value types implement quite a few interfaces, namely IEquatable, IComparable and IConvertible. With .NET 7.0, many more where added in preparation for the support of generic math.

It is correct that if you do something like

int x = 2;
IEquatable<int> eq = x;
if (eq.Equals(3))
{
    // ...
}

a boxing conversion is necessary. However, if you write this like

int x = 2;
if (x.Equals(3)) 
// ...

the compiler will typically emit a direct call to the Equals method, avoiding the boxing. And of course, if you simply write if (x == 3) no boxing is involved too, because the compiler directly inserts the instruction for a numeric equality test.

huangapple
  • 本文由 发表于 2023年4月17日 14:45:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76032352.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定