英文:
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
是的,标准的数值类型实现了相当多的接口,具体包括 IEquatable
、IComparable
和 IConvertible
。在 .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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论